I was trying to understand how pointers work in c when i came across this weird problem.
Now, I wanted to build a linked list. The first thing I did was adding the add function. Once the function add a node to the last node of the list(which it does successfully)
typedef struct linkedLists{
int x;
struct linkedLists *next;
//int (*add)(int) = add;
}linkedList;
void addF(linkedList *l, int y){
linkedList adder = {.x=y};
l->next = &adder;
return;
}
int main(int argc, char** argv) {
linkedList list = {.x=2,.next=NULL};
printf("%d\n",list.x);
addF(&list,3);
printf("%d\n",list.x);
// If you comment this line the result changes to what it's
//expected
printf("%d\n",(*list.next).x);
return (EXIT_SUCCESS);
}
If I run
printf("%d\n",(*list.next).x);
I get 3, which is desired. However, if I run
printf("%d\n",list.x);
printf("%d\n",(*list.next).x);
I get: 2 Random number