c - 两个指针的指针地址相差很大
问题描述
#include <stdio.h>
int main() {
int *p;
void *q;
printf("%p\n", p);
printf("%p\n", q);
}
我编译并运行了上面的 C 代码,这是一次运行的示例输出:
$ ./a.out
0x10ef55025
0x7ffeeb11f52
我立即注意到指针的指针地址和int
指针之间存在巨大差距void
,并且这种行为在代码的多次执行中是持久的。上面的解释有解释吗?
解决方案
p
您永远不会为or分配值q
,因此打印存储在其中的值充其量只能是垃圾。这就是你所看到的。
请注意,如果您按照应有的方式启用警告,您的编译器应该警告您。
$ 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);
^~~~~~~~~~~~~~~~~
如果您尝试打印p
和q
他们自己的位置(而不是他们指向的位置),您想要
printf("%p\n", (void*)&p); // Print the address of `p` itself.
printf("%p\n", (void*)&q); // Print the address of `q` itself.
正如您从上面的警告中看到的那样,printf
's%p
需要强制转换为void*
. 这基本上是您唯一需要投射到void*
.
推荐阅读
- javascript - 相同的端点,由 axios 和 fetch 打包的响应不同。如何转换?
- sorting - 在 Dask Dataframe 中滞后值的最佳方法是什么?
- godot - Godot 3.3.2 - 从父级更改子变量而不重置它们
- android - Android 如何在 Dispatchers.Default 上的 viewModel 中执行 flow.map()
- excel - 需要一个宏在每个设定的时间内自动打开excel中的超链接
- javascript - 使用 jquery 在 js 中运行数据 forEach 并且它没有执行开关中的每个项目
- swift - Firestore 正在创建文档参考,而不是将信息附加到我已经指定的文档
- javascript - 多个字段到单行
- android - What is the point of using view.getRootView().findViewById() inside of onViewCreated in fragment?
- html - 如何在pandoc生成的pdf文件中居中h1和h2 html标题