打印指针地址时%d
和%u
之间有什么区别?
例如:
int a = 5;
// check the memory address
printf("memory address = %d\n", &a); // prints "memory address = -12"
printf("memory address = %u\n", &a); // prints "memory address = 65456"
答案 0 :(得分:26)
答案 1 :(得分:6)
如果我正确理解您的问题,您需要%p
来显示指针正在使用的地址,例如:
int main() {
int a = 5;
int *p = &a;
printf("%d, %u, %p", p, p, p);
return 0;
}
将输出如下内容:
-1083791044, 3211176252, 0xbf66a93c
答案 2 :(得分:4)
答案 3 :(得分:1)
%u用于无符号整数。由于有符号整数地址运算符%d给出的存储器地址是-12,要使用无符号整数获取该值,Compiler将返回该地址的无符号整数值。
答案 4 :(得分:1)
区别很简单:它们会在编译时发出不同的警告消息:
1156942.c:7:31: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=]
printf("memory address = %d\n", &a); // prints "memory add=-12"
^
1156942.c:8:31: warning: format ‘%u’ expects argument of type ‘unsigned int’, but argument 2 has type ‘int *’ [-Wformat=]
printf("memory address = %u\n", &a); // prints "memory add=65456"
^
如果您将指针作为void*
传递并使用%p
作为转换说明符,则不会收到任何错误消息:
#include <stdio.h>
int main()
{
int a = 5;
// check the memory address
printf("memory address = %d\n", &a); /* wrong */
printf("memory address = %u\n", &a); /* wrong */
printf("memory address = %p\n", (void*)&a); /* right */
}