给出下面的代码为什么a和b的值会改变..p1和p2存储的是a和b的地址,为什么当p1和p2改变时a和b会改变
#include <stdio.h>
int main(int argc, char** argv)
{
//&a stores address
//*p1 is a pointer
int a = 5, b = 10;
int *p1, *p2; //p1 and p2 are 2 pointers which can store int addressses
p1 = &a; //now p1 and p2 stores address of a and b
p2 = &b;
printf("p1 storing address of a = %d\n", *p1);
printf("p2 storing address of b = %d\n", *p2);
*p1=30;
*p2=40;
printf("p1 assigning values to p1 pointer = %d\n", *p1);
printf("p2 assigning values to p2 pointer= %d\n", *p2);
printf("a whose value is = %d\n", a);
printf("b = %d\n", b);
}
最佳答案
我认为如果您还打印指针本身而不仅仅是它们的内容,事情会更清楚。您可以为此使用 %p
说明符。
#include <stdio.h>
int main()
{
int a = 10;
int b = 20;
int *p = &a;
int *q = &b;
printf("1) p is %p\n", p);
printf("1) q is %p\n", q);
printf("1) a is %d\n", a);
printf("1) b is %d\n", b);
p = q;
/* At this point, I changed the value of p so that it points to `b`
just like `q` does. `a` and `b` are still unchanged. */
printf("2) p is %p\n", p);
printf("2) q is %p\n", q);
printf("2) a is %d\n", a);
printf("2) b is %d\n", b);
*p = 30;
/* Now that p points to `b`, dereferencing the pointer will affect `b`
instead of `a` */
printf("3) p is %p\n", p);
printf("3) q is %p\n", q);
printf("3) a is %d\n", a);
printf("3) b is %d\n", b);
}
当你说 *p = something
时,你正在分配 p
指向的内存位置(可能是 a
或 b
取决于您的设置方式)。另一方面,如果您执行 p = q
,您会更改指针本身,而不是它指向的内容。
关于c - 试图理解指针的引用和地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36519740/