繁体   English   中英

两个指针的指针地址相差很大

[英]Large difference in pointer address between two pointers

#include <stdio.h>

int main() {
  int *p;
  void *q;
  printf("%p\n", p);
  printf("%p\n", q);
}

我编译并运行了上面的 C 代码,这是一次运行的示例 output:

$ ./a.out
0x10ef55025
0x7ffeeb11f52

我立即注意到int指针和void指针的指针地址之间存在巨大差距,并且这种行为在代码的多次执行中持续存在。 上面的解释有解释吗?

您永远不会为pq分配值,因此打印存储在其中的值充其量是垃圾。 这就是你所看到的。

请注意,如果您按照应有的方式启用警告,您的编译器应该警告您。

$ gcc -Wall -Wextra -pedantic a.c -o a
a.c: In function ‘main’:
a.c:6:12: warning: format ‘%p’ expects argument of type ‘void *’, but argument 2 has type ‘int *’ [-Wformat=]
   printf("%p\n", p);
           ~^
           %ls
a.c:6:3: warning: ‘p’ is used uninitialized in this function [-Wuninitialized]
   printf("%p\n", p);
   ^~~~~~~~~~~~~~~~~
a.c:7:3: warning: ‘q’ is used uninitialized in this function [-Wuninitialized]
   printf("%p\n", q);
   ^~~~~~~~~~~~~~~~~

如果您尝试打印pq本身的位置(而不是它们指向的位置),您想要

printf("%p\n", (void*)&p);   // Print the address of `p` itself.
printf("%p\n", (void*)&q);   // Print the address of `q` itself.

正如您从上面的警告中看到的, printf%p需要强制转换为void* 这基本上是您唯一需要转换为void*的时间。

暂无
暂无

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

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