Why the result of this code is the same when the arg is different?

心已入冬 提交于 2020-05-17 07:06:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!