Error while trying to assign incompatible types
-
09-12-2019 - |
Question
The error I get when I try to print out this list is an incompatible type error. I tried casting it as struct macro, static struct macro, a pointer, and none of it work.
struct macro {
struct macro *next;
char * macro_name;
char * macro_body;
};
static struct macro macro_list = {
.next = NULL,
.macro_name = NULL,
.macro_body = NULL
};
//--------------------------------------------------------------------------------
void macro_list_print(void){
printf("Printing macro_list\n");
if(macro_list.next == NULL){
printf("--No macros\n");
}
struct macro p = macro_list;
while(p.next != NULL){
printf("%s %s\n",p.macro_name,p.macro_body);
p = macro_list.next; //This line gives me the error.
}
}
I can't figure out what to do here. Any help would be appropriated thanks.
Solution
p
is a struct macro
whereas macro_list.next
is a struct macro*
. Change to:
struct macro* p = ¯o_list;
while(p != NULL){
printf("%s %s\n",p->macro_name,p->macro_body);
p = p->next;
}
I made the following additional changes:
macro_list.next
top->next
, otherwise it would never have gotten past the second item in the list.- changed the condition in the
while
top != NULL
, otherwise it would not have processed the last element in the list as it was checkingp->next != NULL
OTHER TIPS
p is of type macro
, but macro_list.next is of type macro *
.
Instead of defining macro_list as a struct macro
(with empty name and body) I'd define it as a struct macro *
.
Also when you walk through the list, you want p = p->next;
to get to the next item in the list. As it is, you're always assigning macro_list.next
, so you'll repeatedly look at the first item in the list.
To walk a linked list like this, I'd normally use:
struct macro *macro_list = NULL;
for (p=macro_list; p!= NULL; p=p->next)
printf("%s %s\n", p->macro_name, p->macro_body);
I suppose that next is a pointer, so:
void macro_list_print(void){
printf("Printing macro_list\n");
if(macro_list.next == NULL){
printf("--No macros\n");
}
struct macro* p = ¯o_list;
while(p->next != NULL){
printf("%s %s\n",p->macro_name,p->macro_body);
p = macro_list.next;
}
}