so I’m creating a linked list counter for fun, here’s my program.
WHAT I WANT:
I want it to give me the correct count
WHAT I GET:
The following errors:
linkedlist.c:12: warning: assignment from incompatible pointer type
linkedlist.c:14: warning: assignment from incompatible pointer type
linkedlist.c: In function ‘main’:
linkedlist.c:22: warning: assignment from incompatible pointer type
linkedlist.c:23: warning: assignment from incompatible pointer type
linkedlist.c:24: warning: assignment from incompatible pointer type
linkedlist.c:25: warning: assignment from incompatible pointer type
MY CODE
I realize that this isn’t a good way to instantiate a linked list. That doesn’t matter though, what I’m stressing is that my counter works.
I have made some amendments to my code. No, this is not a c++ program, it actually is a c program.
My program now works, but I would like to know why I receive so many warnings about an incompatible pointer type. Any ideas? I’m sure it’s a simple problem.
#include <stdio.h>
typedef struct {
int x;
char *y;
struct CELL *next;
} CELL;
int list_length(CELL *head){
int counter;
CELL *current;
if(head->next!=NULL){
current=head->next;
for(counter=1;current!=NULL;++counter){
current=current->next;}}
else
return 0;
return counter;}
main(){
CELL a,b,c,d,e;
a.next=&b;
b.next=&c;
c.next=&d;
d.next=&e;
e.next=NULL;
int l=list_length(&a);
printf("The list length is %d \n",l);
}
First, to get this program to compile…
struct CELLin your type declarationschar *instead ofstring(string isn’t a C data type)As for the algorithm in
list_length(), you want something more like this:You should also note that your
instantiate()function returns a pointer to stack-allocated memory resulting in undefined behavior. Move the code frominstantiate()into the main function.Here is a complete working program:
To fix the warnings in your latest iteration you need to declare
CELLsomething like this: