This question already has answers here:
Can a local variable's memory be accessed outside its scope? (20 answers)
How to access a local variable from a different function using pointers? (10 answers)
Closed 3 years ago.
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
JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)