【发布时间】:2019-03-23 10:09:42
【问题描述】:
假设这样一个sn-p的最小代码:
#include <stdio.h>
int main(void)
{
int a = 2;
int b = a;
printf("a = %d, &a = %d", a, &a);
printf("b = %d, &b = %d", b, &b);
return 0;
}
我运行它并得到错误报告:
test.c:6:31: warning: format specifies type 'int' but the argument has type 'int *' [-Wformat]
printf("a = %d, &a = %d", a, &a);
~~ ^~
test.c:7:31: warning: format specifies type 'int' but the argument has type 'int *' [-Wformat]
printf("b = %d, &b = %d", b, &b);
~~ ^~
2 warnings generated.
我假设a = 2 b = 2 等同于a = b = 2,但编译器提醒信息很难理解。
【问题讨论】:
-
要打印指针,请使用
%p而不是%d。&a不是int,而是指向int的指针。 -
您的标题具有误导性。正如您在编译输出中看到的那样,这些是警告,由另一行产生。
-
&a是指向 int 的指针,因此在打印时使用%p并将类型转换为void*作为 p conversion specifier requires an argument of type void * -
编译器会在有错误的行下划线,并用简单的英文说明原因。
-
我不得不说,随着编译器消息的传递,该消息特别有用且易于阅读。
标签: c