Hello to everyone
I am creating a linked list that contains id and name information. I am having a runtime error when I initialize list_node * newlist = {NULL} already contains it has information just like list_node newnode and it doesn't allow me to initialize in null.
. What should I do to initialize everything in NULL without new data.
typedef struct nodo list_node; struct nodo { int count; char name[20]; struct nodo *p1; }; struct nodo *crearlista_ssid(char *[5]); struct nodo * crearlista_ssid(char *array[5]) { char *lista2; list_node *newlist={NULL},*aux={NULL}; for(int i=0;i<=4;i++) { list_node *newnode= (list_node*) malloc(sizeof(list_node)); if(newnode) { newnode->count=i+1; lista2= strtok(array[i], ","); lista2= strtok(NULL, ","); strcpy(newnode->name,lista2); newnode->p1=NULL; if(newlist->p1==NULL) newlist=newnode; else { aux=newlist; while(aux->p1!=NULL) { aux=aux->p1; } aux->p1=newnode; } } } return newlist; }
Change your test for newlist having no items in it.
instead of if (newlist->p1==NULL)
use
if (newlist == NULL)
thank you Robert,
Now I can create the first two elements of the list but in the third one the increase of the pointer does not work, is not working moving until NULL.
else{ while(newlist->p1!=NULL) { newlist=newlist->p1; } newlist->p1=newnode; }
list_node *newlist={NULL},*aux={NULL};
This init is wrong. It must be list_node *newlist = NULL;
What you do is, that you create a list_node on the stack and fill it with zero. So in case you get no memory, you return a pointer to a (then) killed stack variable.