When I run the program below, it prints “one: 1”, instead of “one : 1, two: 2”, as I had expected. Anyone know what’s going on here? I am trying to create a function that will allow me to create as many linked lists as possible instead of just declaring global heads.
struct Node {
int value;
char label[10];
node *next;
};
typedef struct Node node;
int add(int data, char name[], node *head) {
node *newNode = (node *)malloc(sizeof(node));
if (newNode != NULL) {
newNode->value = data;
strcpy(newNode->label, name);
newNode->next = head;
head = newNode;
}
}
node* createNewLinkedList(int d, char *name) {
node *newNode = (node *)malloc(sizeof(node));
newNode->value = d;
strcpy(newNode->label, name);
newNode->next = NULL;
return newNode;
}
int main() {
node *head1 = createNewLinkedList(1, "one");
add(2, "two", head1);
iterate(head1);
}
You are passing a pointer to the node. Like all parameters in C, it is passed by value, therefore
head = newNode;has no effect in the caller.You need to change the signature to accept
node **head, and add a level of indirection in order to make the changes inaddbe reflected in themain.Of course you’ll need to pass
&head1to theaddmethod:add(2, "two", &head1);P.S. Since you are adding {2,”two”} to the front of the list, your output will be “two: 2, one : 1”