【发布时间】:2015-10-25 09:11:38
【问题描述】:
我知道 %d 代表 int,%u 代表 unsigned int,%p 代表地址。 但我的问题是我们可以在 Windows 机器上使用 %u,%d 打印地址,但在 Linux 上却不能这样做。
例如:
#include<stdio.h>
int main() {
int x=15;
int *p;
p=&x;
printf("%d \n",x);
printf("%d \n",&x);
printf("%u \n",&x);
printf("%p \n",p);
printf("%x \n",p);
printf("%u \n",&p);
return 0;
}
输出:
15
2358812
2358812
000000000023FE1C
23fe1c
2358800
可以看出,使用 %d 和 %u 将十六进制值(23fe1c)更改为十进制。
但完全相同的代码在 Unix/Linux 上会出错。
错误:
format (%d) expects arguments of type 'int', but argument 2 has type 'int*'
【问题讨论】:
-
将不匹配的数据提供给
printf会导致未定义的行为。您在 Windows 上的编译器意外接受了它,但 Linux 上的编译器没有。 -
请注意,
%p用于打印void*,因此您应该在将指针传递给printf之前将其转换为printf("%p \n",(void*)p);,即printf("%p \n",(void*)p); -
为了清楚起见,您不能使用
%d打印指针值,因为指针不是整数。整数不是指针。仅仅因为使用%d打印指针在某些平台上工作并不意味着它可以在任何地方工作。但是将指针视为整数是错误的 - anywhere。当您开始进行 64 位编程时,您将很难学到这一点。