C: add an element at the end of a list

Viewed 57

I would like to add an item at the end of the list. I don't understand why the program is compiling but then something goes wrong and stops the execution. Commenting on the last line of the function everything works, but clearly it loses the pointer to the last element of the list. I think it has something to do with the impossibility of "ptr" to modify its "pointer". Could someone help me? thanks

void add_element(struct element *ptr, int item) {

while(ptr != NULL) {
    ptr = ptr->pointer;
}
struct element *ptr2;
ptr2 = (struct element*)malloc(sizeof(struct element));
ptr2->number = item;
ptr2->pointer = NULL;
ptr->pointer = ptr2; }
1 Answers

At the last line of your code you wan't to assigne value to ptr->pointer, but in your while loop your condition said: if ptr is not NULL we continue, so after go out of your while loop ptr is equal to NULL.

To fix you probleme use this while loop:

while(ptr->pointer != NULL) {
    ptr = ptr->pointer;
}
Related