c - 但是,当使用 %d 而不是 %p 时,究竟打印了什么?
问题描述
正如代码所示,当调用 %d 时打印的这个随机的、看似垃圾的数字是向量的下一个元素的间隔“sizeof(type)”数字。
但是如果我转换第一个元素的十六进制地址,它与数字不匹配。
那么如果不是以十进制表示的地址,那么这个打印的数字究竟是什么?
0x7ffcd6b154c0 == 140723910431936
而打印的小数点是 -693021504
#include <stdio.h>
void main(){
int x[] = {2, 5}, *ptr = &x;
printf("%d\n", ptr);
printf("%p\n", ptr);
printf("\n%d %d\n", ptr, (ptr + 1));
}
解决方案
这是一个掷骰子,因为您调用了Undefined Behavior:
C11 标准 - 7.21.6.1 fprintf 函数 (p9)
"If a conversion specification is invalid, the behavior is undefined. If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined."
很可能会打印的是系统上的实际指针地址,其中指针的大小与int
(例如 x86)相同,否则,如果幸运的话,您将从 8 字节指针中打印 4 字节。
推荐阅读
- javascript - Three.js:如何使用平面将物体分成两部分?
- java - PowerMock throwing class not found 在测试类中的异常
- javascript - 唯一键是唯一的,已分配给 key prop,但仍然出现错误...但仅在一个组件中
- list - 取第二个元素的列表的子列表
- javascript - 覆盖 react-native 样式表样式
- google-apps-script - Google Apps脚本在公式中转换日期
- flutter - Swiper 小部件 itemCount 从无限变化
- c++ - std::atomic 和 std::mutex 的相对性能
- javascript - 如何在javascript中访问c#模型数据
- compiler-errors - 为什么 HDF5 在这里给出“参数太少”的错误?