开发 C++在指针地址的情况下给出不同的结果

发布于 2024-12-22 21:59:24 字数 553 浏览 1 评论 0原文

我有以下一组代码

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

南巷近海 2024-12-29 21:59:24

两者不同,因此输出也不同。

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 pointer p1 itself is stored in memory.

陈甜 2024-12-29 21:59:24

最初,p1 存储 x 的地址(您通过 &x 获得)。稍后您设置 p1 来存储空地址。

在第一个代码段中,您决定不打印 p1存储的地址,而是打印 p1地址 本身p1 是一个与其他变量一样的变量,就像其他变量一样,&p1 将为您提供该变量的地址。这与存储在其中的值不同,后者可以通过 p1 访问,并且是第二个片段打印的内容。

I like pictures

与任何其他变量一样,您无法更改变量 p1 的地址,您只能改变它存储的值,而对于指针来说,值恰好是一个地址。

Initially p1 stores the address of x (which you obtained with &x). Later on you set p1 to store a null address.

In the first snippet you decided to print not the address stored in p1, but the address of p1 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 with p1 and is what the second snippet prints.

I like pictures

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.

几味少女 2024-12-29 21:59:24
p1=0;

将把指向“p1”的指针设置为零,而不是它的内容,这应该由

*p1=0;
p1=0;

will set the pointer that points to "p1" to zero, not the content of it which should be done by

*p1=0;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文