list - Unexpected error:"Dereferencing pointer to incomplete type" with code::blocks, c language -


i'm doing exercise base c programming exam , error: "dereferencing pointer incomplete type", using code::blocks. here code:

struct listplot{ char name[25]; char surname[25]; int age; struct listplot *next; struct listplot *prev; };  struct listplot *list;  struct listplot *init(void) {     list=malloc(sizeof(list));     list->next=null;     list->prev=null;     return list; };  struct listplot *addelement(struct listplot *input) {     printf("\nnew element, name:\n");     gets(input->name);     printf("\nsurname:\n");     gets(input->surname);     printf("\nage:\n");     scanf("%d", &input->age);     struct listplot *newelement=malloc(sizeof(list));     *input->next=*newelement; //this line error occurs     newelement->next=null;     *newelement->prev=*input; }; 

this function addelement should take listplot pointer input, insert name surname , age, create new element of list , return it's pointer. don't understand what's wrong it... apologize stupidity. question, if write input->next=newelement; instead of *input->next=*newelement; no error warning: "assignment incompatible pointer type [enabled default]". i'm sorry again ineptness, must ask meaning of , difference between 2 lines. hope don't mind helping me , thank in advance.

struct listplot{   char name[25];   char surname[25];   int age;   struct listplot *next;   struct listplot *prev; }; 

you have typo above. struct listplot *next should struct listplot *next (with capital p). compiler doesn't know struct listplot so, naturally, cannot dereference pointer it.


list=malloc(sizeof(list)); 

this wrong. size should size of whatever list points to, not list itself. should test return value of malloc() before using it:

struct listplot *init(void) {   list = malloc (sizeof *list);   if (list) {     list->next=null;     list->prev=null;   }   return list; } 

struct listplot *addelement(struct listplot *input) {   printf("\nnew element, name:\n");   gets(input->name); 

gets() inherently unsafe , should (almost) never used. if input longer expect, keep writing outside buffer. better alternative fgets().


  ....    struct listplot *newelement=malloc(sizeof(list)); 

wrong size again. better:

  struct listplot *newelement = malloc(sizeof *newelement); 

take sizeof identifier on left asterisk in front of it, , automatically right size (for 1 element). , reader doesn't need lookup list is.


  *input->next=*newelement; //this line error occurs   newelement->next=null;   *newelement->prev=*input; 

these lines should be:

  input->next = newelement;   newelement->next = null;   newelement->prev = input; } 

also, have semicolons @ end of function definitions. typos? don't think compile.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -