I do not understand why this program is not working and the elements were not inserted into the List as intended.
Every time, when I am debugging, I see that when I go to the main
method after the 'insert' method, the Linked List is still empty and I do not understand why because I think it should be well because I am using pointers (It seems like a 'Dangling Pointer' case, but if it is, I do not understand why).
Maybe should I use double star (**)? If yes, why in arrays it does not matter?
Here is the source code:
#include <stdio.h>
#include <stdlib.h>
struct A{
int val;
struct A* next;
} A;
void insert(struct A* L, int newVal) {
if (L == NULL) {
L = (struct A*) malloc(sizeof(struct A));
L->val = newVal;
L->next = NULL;
}
else {
struct A* p = L;
while (p->next != NULL) {
p = p->next;
}
p->next = (struct A*) malloc(sizeof(struct A));
p->next->val = newVal;
p->next->next = NULL;
}
}
void printA(struct A* printed) {
struct A* p = printed;
while (p != NULL) {
printf("%d\n", p->val);
p = p->next;
}
}
int main() {
struct A* L = NULL;
insert(L, 1);
printf("1 success\n");
insert(L, 2);
printf("2 success\n");
insert(L, 3);
printf("3 success\n");
insert(L, 4);
printf("4 success\n");
insert(L, 5);
printf("5 success\n");
printf("\n\n\n");
printA(L);
return 0;
}
Thank You.