list - How do I pass a pointer (that points to a structure) to a function? -


i want create linked list in c, when use code below, gcc throws error:

error: invalid type argument of '->' (have 'struct list')

the code is:

#include <stdio.h> #include <stdlib.h>   struct list{     int age;     struct list *next; };   void create_item(int *total_items,                   struct list where_is_first_item,                  struct list where_is_last_item) {      struct list *generic_item;     generic_item = malloc(sizeof(struct list));     printf("\nage of item %d: ", (*total_items)+1);     scanf("%d", &generic_item->age);      if(*total_items == 0){          where_is_first_item->next=generic_item;         where_is_last_item->next=generic_item;         printf("\nitem created\n");     }     else{          where_is_last_item->next=generic_item;         printf("\nitem created\n");     }  int main (void){     struct list *where_is_first_item;     struct list *where_is_last_item;     int total_items=0;     printf("\n\n\tcreate new item\n");     create_item(&total_items, where_is_first_item, where_is_last_item);     total_items++;     return 0; } 

void create_item(int *total_items, struct list *where_is_first_item, struct list *where_is_last_item)  

add star!

you referencing invalid memory because allocate generic_item reference where_is_first_item. where_is_first_item not allocated to. try where_is_first_item = generic_item; before use where_is_first_item.

you find pointers in main function remain unmodified because pointer values being passed. here gets confusing/interesting: if want pointers in main modified need pass pointers to pointers: struct_list **where_is_first_item. trust me, head in.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -