【发布时间】:2017-08-08 17:03:26
【问题描述】:
我正在测试这段代码,但为什么完全没有错误?
#include <stdio.h>
int main()
{
int a = 1025;
int *p;
p = &a;
// now I declare a char variable ,
char *p0;
p0 = (char*) p; // type casting
printf("", sizeof(char));
// is %d correct here ?????
printf("Address = %d, value = %d\n", p0, *p0);
}
我的问题:
%d 在这里正确吗?既然%d 是整数而不是字符,为什么完全没有错误?
【问题讨论】:
-
实际上问题出在您传递地址的第一个
%d:您应该使用%p。printf("Address = %p, value = %d\n", (void *)p0, *p0);对于第二个char值刚刚提升为int。 -
此外,错误/警告还取决于您如何编译代码:使用
gcc -Wall -Wextra -pedantic-errors test.c -o test -std=c11 -g,您有warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘char *’ [-Wformat=] printf("Address = %d, value = %d\n", p0, *p0);
标签: c printf format-specifiers