开发 C++在指针地址的情况下给出不同的结果
我有以下一组代码
int main(){
int x = 36;
int const * p1;
p1 = &x;
printf("Values at p1: %d\n", *p1);
p1=0;
printf("Addresses pointed to by p1: %p ", &p1);
return 0;
}
给出
Addresses pointed to by p1 gives 0028FF480
int main(){
int x = 36;
int const * p1;
p1 = &x;
printf("Values at p1: %d\n", *p1);
p1=0;
printf("Addresses pointed to by p1: %p ", p1);
return 0;
}
p1 指向的地址给出 00000000
为什么会有这样的差异..?我认为两者都会给我相同的值。
I have a following set of codes
int main(){
int x = 36;
int const * p1;
p1 = &x;
printf("Values at p1: %d\n", *p1);
p1=0;
printf("Addresses pointed to by p1: %p ", &p1);
return 0;
}
gives
Addresses pointed to by p1 gives 0028FF480
int main(){
int x = 36;
int const * p1;
p1 = &x;
printf("Values at p1: %d\n", *p1);
p1=0;
printf("Addresses pointed to by p1: %p ", p1);
return 0;
}
Addresses pointed to by p1 gives 00000000
Why such a difference..?I thought both will give me same value.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
两者不同,因此输出也不同。
p1
返回指针指向的变量的地址。&p1
返回指针p1
本身在内存中存储的地址。Both are different hence the difference in output.
p1
returns the address of the variable pointed by the pointer.&p1
returns the address where the pointerp1
itself is stored in memory.最初,
p1
存储x
的地址(您通过&x
获得)。稍后您设置p1
来存储空地址。在第一个代码段中,您决定不打印
p1
中存储的地址,而是打印p1
的地址 本身。p1
是一个与其他变量一样的变量,就像其他变量一样,&p1
将为您提供该变量的地址。这与存储在其中的值不同,后者可以通过 p1 访问,并且是第二个片段打印的内容。与任何其他变量一样,您无法更改变量
p1
的地址,您只能改变它存储的值,而对于指针来说,值恰好是一个地址。Initially
p1
stores the address ofx
(which you obtained with&x
). Later on you setp1
to store a null address.In the first snippet you decided to print not the address stored in
p1
, but the address ofp1
itself.p1
is a variable like any other, and just like with the rest of them,&p1
will give you the address of that variable. That's different from the value stored in it, which is accessible withp1
and is what the second snippet prints.Like any other variable, you cannot change the address of the variable
p1
, you can only change the value it stores, and in the case of a pointer it just so happens that value is an address.将把指向“p1”的指针设置为零,而不是它的内容,这应该由
will set the pointer that points to "p1" to zero, not the content of it which should be done by