首页 > 解决方案 > 但是,当使用 %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));
}

标签: cpointersprintfmemory-address

解决方案


这是一个掷骰子,因为您调用了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 字节。


推荐阅读