+ 1
I am new here please explain this please please please
#include <stdio.h> #include <stdlib.h> int a = 5, b = 10; void change1(int *p); void change2(int **pp); int  main() { int x=20, *ptr=&x; printf("%d  ",*ptr); change1(ptr); printf("%d  ",*ptr);// answer is not 5 here why??????????????????? change2(&ptr); printf("%d\n",*ptr); } void change1(int *p) { p = &a; } void change2(int **pp) { *pp = &b; return 0; }
4 Answers
+ 3
A pointer variable is a stack variable like any other "normal" variable. That means passing by value versus passing by reference applies to pointers as well.
So if you just pass the pointer into the first change() function, it is copied, and the copied pointer is then changed to point to 'a', however, the original pointer is not affected, and still points to 'x'. This is classic passing by value.
On the other hand, when passing the pointer into the second version of change(), you pass it by reference since you pass the pointer's address, and by this, the original pointer is affected when the assignment is made.
Understanding the difference betwen these two ways of passing a variable in C is crucial for this, so try looking it up if you need more information on the topic. There is plenty on the net.
Mateusz Kempa There is always someone stupid enough, yes. :)
+ 3
Me too
0
why would it be 5? and what is this mess anyway? you honestly think someone will care to help if you don't even care to format your question in readable form?
0
Damn ruchi tripathi , consider yourself lucky one this time. Seeing such kindness and understanding from our dear mod Shadow simply inspired me to be a better men, so i too, am gonna try to help you. In addition to Shadow's tips it is worth pointing out that global variables are indeed, seen in whole program. However, in the scope of main function you defined another x variable, but a local one. So, now untill main goes out of scope it's the local x variable that you are referencing. (fyi, you could still use ::x syntax to bypass that behavior). I don't know if this was the reason of your confusion, because frankly i can't tell if you defined them this way on purpose. I don't think anybody can when i'm looking at this masterpiece of code.
Have fun at sololearn, keep grinding and for godsake try to make a solid, clean posts next time you ask any questions.