Reputation: 233
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);
}
Upvotes: 0
Views: 153
Reputation: 814
First, to get this program to compile...
struct CELL
in your type declarationschar *
instead of string
(string isn't a C data type)As for the algorithm in list_length()
, you want something more like this:
int list_length(struct CELL *head)
{
int counter = 0;
while (head) {
head = head->next;
++counter;
}
return counter;
}
You should also note that your instantiate()
function returns a pointer to stack-allocated memory resulting in undefined behavior. Move the code from instantiate()
into the main function.
Here is a complete working program:
#include <stdio.h>
struct CELL {
struct CELL *next;
};
int list_length(struct CELL *head)
{
int counter = 0;
while (head) {
head = head->next;
++counter;
}
return counter;
}
int main(void)
{
struct CELL a, b, c, d, e;
a.next = &b;
b.next = &c;
c.next = &d;
d.next = &e;
e.next = NULL;
printf("The list length is %d \n", list_length(&a));
return 0;
}
To fix the warnings in your latest iteration you need to declare CELL
something like this:
typedef struct CELL_ {
int x;
char *y;
struct CELL_ *next;
} CELL;
Upvotes: 3
Reputation: 225012
You haven't included <string>
and you're missing a semicolon at the end of the structure definition. Your code has other bugs too, like returning pointers to local variables. It also appears to me that this is a C++ program, but you've tagged it C.
Upvotes: 1