简体   繁体   English

有人可以用 C 解释一下这段代码吗?

[英]Can someone explain this little piece of code in C?

The output is :输出是:

25
28ff1c
28ff1c
25

I don't understand why.我不明白为什么。 The first value and address are understandable, but why is the second output the same?第一个值和地址可以理解,但为什么第二个输出相同? Doesn't the address of g get changed in the function? g 的地址在函数中没有改变吗?

float add(int *x, int y)
{
    static float s = 100.f;
    s=s+y;
    x=x+y;
    return s;
}



int main()
{

    int g=25;
    printf("%d\n",g);
    printf("%x\n",&g);

    add(&g,35.2);

    printf("%x\n",&g);
    printf("%d\n",g);

return 0;
} 

You cannot change the address of a variable with a single pointer (ie int *x).您不能使用单个指针(即 int *x)更改变量的地址。 As suggested in comments this may not have been your intention so sorry if you know this.正如评论中所建议的那样,如果您知道这一点,这可能不是您的本意。

To change the address you must use a double pointer, you must deference it once to get the address and to access the value you must deference it twice.要更改地址,您必须使用双指针,您必须对其进行一次访问以获取地址并访问该值,您必须对其进行两次访问。

void func(int **x)
{
    int value = **x;
    uintptr_t address = *x;

    *x = address + sizeof(int);
}

...but why is the second output the same? ...但为什么第二个输出相同?

Because your original code:因为你的原始代码:

float add(int *x, int y)
{
    static float s = 100.f;
    s=s+y;
    x=x+y; // changing the pointer
    return s;
}

Does not change the value pointed to by the address of x.不改变 x 的地址指向的值。
Change the code as shown to allow the value to be updated:如图所示更改代码以允许更新值:

float add(int *x, int y)
{
    static float s = 100.f;
    s=s+y;
    *x=*x+y; //changing the value pointed to by the pointer
             //(i.e., the value exposed via the de-referenced pointer is 
             //modified to a new value.)
    return s;
}

Given:鉴于:

 int g=25;
 ...
 add(&g,35.2);

Results after change:更改后的结果:

25 25
81feb8 81feb8
81feb8 81feb8
60 60

Note: Because the type of the 2nd argument: float add(int *x, int y)注意:因为第二个参数的类型: float add(int *x, int y)
is int , 35.2 is truncated to 30 , resulting the in the sum beingint35.2被截断为30 ,导致总和为
60 instead of 60.2 60而不是60.2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM