Search code examples
ctypesvariable-assignmentincompatibility

Error while trying to assign incompatible types


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 = &macro_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 to p->next, otherwise it would never have gotten past the second item in the list.
    • changed the condition in the while to p != NULL, otherwise it would not have processed the last element in the list as it was checking p->next != NULL