int x = 5;
int y = 6;
int *p = &x;
*p = x + y;
p = &y;
*p = x + y;
printf("%d,%d", x, y);
我能看懂前三行。我知道 int *p = &x;
表示指针 p
指向 x
的内存地址。但是我无法理解接下来的 4 行代码。此代码的输出是:
11,17
但是我无法理解怎么办?谁能给我解释一下。
最佳答案
A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location.
当你这样分配时,
int *p=&x;// It will point to the address of x variable.
在*p
中所做的任何更改,都会影响内存。因此,当您使用 x
访问它时,它具有值。
*p=x+y; // It's equivalent x=x+y;
然后y
也喜欢这个。
现在 x
的值为 11
。 p=&y;
*p=x+y;// It's equivalent to y=x+y;
所以现在 x 的值为 11
,y 的值为 5
。所以结果是 17
。
关于无法理解涉及指针的 C 程序的一小部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29096590/