Hi everyone!
I'm trying to write a program that lets the user append nodes at the end of a linked list. It kinda works but the main problem is that it doesn't actually create any new nodes later on, the function I've written creates one new node and then just keeps on changing its values over and over again.
Code:
static void append(Node *_tail, unsigned _id) {
Node temp = { .id = _id, .next = NULL };
if (_tail == NULL) {
_tail = &temp;
} else {
_tail->next = &temp;
_tail = &temp;
}
}
I've also tried dynamically allocating memory for the nodes with malloc() and calloc() but that gave me the same results. What am I doing wrong?
Here's the main() function if you were wondering.
Code:
int main(void) {
unsigned input;
Node n3 = { .id = 3, .next = NULL };
Node n2 = { .id = 2, .next = &n3 };
Node n1 = { .id = 1, .next = &n2 };
Node *head = &n1, *tail = &n3;
for (;;) {
printf("Enter an ID: "), scanf("%u", &input);
append(tail, input);
for (Node *i = head; i != NULL; i = i->next) {
printf("ID: %u\n", i->id);
}
}
return 0;
}