So i have my definition of the list as a global variable:
typedef struct center {
char center_name[100];
char hostname[100];
int port;
struct center *next_center;
} center;
I need to add elements to the list. But these elements that i need to add are on a file, so:
int main(int argc, char** argv) {
center *head = NULL;
parse(argv, head);
}
parse is a function, which read the file and add those read elements to a new center (all of this works, it double checked)
void parser (char** argv, center *head) {
//read the elements i need to add
//creates a newCenter and adds the elements read to the new center
//this far it works
addToCenter(newCenter, head);
}
where:
addToCenter(center *newCenter, center *head){
//adds newCenter to the list
if (head == null)
head = newCenter;
else {
//find last element
lastelement.next_center = newCenter;
}
}
Everything works, except that the list on Main always return as null. In other words, the reference is not being modified. I dont understand why, because i am passing a pointer to the list.
another solution i though is to create the head variable of the list as a global variable, but its better to avoid those situations.
Thanks in advance.
Your list head is being passed by value. You need to pass the head pointer by address in case it is modified (which it will be).
Example:
should be:
Likewise with parse:
And finally back in main: