问题描述
如果已经有答案,可以随意将其重复,因为我还没有找到答案.
这是代码(第一个代码):
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;
}
上面的代码的结果是:
5
9
我的问题是,为什么不是
And my question is, why it isn't
5
5
?
我的意思是,据我所知,要更改 boi
的 val
,需要 void chg(是的,大声笑)
和chg(& boi);
,而不是 void chg(yay * lol)
.显然我不太了解指针.
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;
}
推荐答案
Boi指向具有val 5的堆中的内存位置(例如0x1233).u在chg函数中传递相同的内存位置(0x1233)并修改相同堆位置的值为9.这就是为什么您看到boi-> val为9.的原因.
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..
这篇关于当arg不同时,为什么此代码的结果相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!