问题
Feel free to make this post as a duplicate if there's already an answer for it because I haven't found the answer.
Here's the code (first code):
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int val;
} yay;
yay* New (int val)
{
yay *Node=(yay*) malloc (sizeof (yay));
Node->val=val;
return Node;
}
void chg (yay *lol) {lol->val=9;}
int main ()
{
yay *boi=New (5);
printf ("%d\n", boi->val);
chg (boi);
printf ("%d\n", boi->val);
return 0;
}
The result of the code above is:
5
9
And my question is, why it isn't
5
5
?
I mean, from what I know, to change val
of boi
requires void chg (yay **lol)
and chg (&boi);
in main ()
, not void chg (yay *lol)
. I don't understand much of pointer apparently.
What's the difference with this one (second code)?
...
void chg (yay **lol) {(*lol)->val=9;}
int main ()
{
yay *boi=New (5);
printf ("%d\n", boi->val);
chg (&boi);
printf ("%d\n", boi->val);
return 0;
}
回答1:
Boi points to memory location(eg. 0x1233) in heap which has val 5.. u pass the same memory location (0x1233) in chg function and modify the value of same heap location to 9.. thats why u see the boi->val is 9..
来源:https://stackoverflow.com/questions/61747555/why-the-result-of-this-code-is-the-same-when-the-arg-is-different