编译器在打印变量地址时发出警告 [英] Compiler gives warning when printing the address of a variable
问题描述
我制作了一个非常简单的程序来打印两个变量的地址。
I made a very simple program to print the address of two variables.
#include<stdio.h>
int main()
{
int a,b;
printf("%u\n%u",&a,&b);
return 0;
}
但是,Clang-3.7编译器给出警告:
But, the Clang-3.7 compiler gives warning as:
warning:format指定类型'unsigned int',但参数类型为'int *'[-Wformat]`
warning: format specifies type 'unsigned int' but the argument has type 'int *' [-Wformat]`
但是,当我使用GCC-5.x进行编译时,它没有发出警告。其中哪一个是正确的?
But, when I compiled with GCC-5.x, it gave no warnings. Which of them is correct?
我知道的一件事是,做 unsigned int num =& a;
是错误的,因为地址只能被存储在一个指针中。但是,编译器在打印地址时发出警告是否正确?
One thing I know is that doing unsigned int num=&a;
would be wrong as address can only be stored in a pointer. But, is it correct for the compiler to give warning when printing the address?
推荐答案
%p
是打印地址的正确格式说明符:
%p
is the correct format specifier to print addresses:
printf("%p\n%p",(void*)&a, (void*)&b);
C标准要求对应于%p $ c的自变量$ c>的类型应为
void * 。这样就可以了。
The C standard requires that the argument corresponding to %p
should be of type void*
. So the casts are there.
C11,参考:
p参数应为指向void的指针。指针
的值以
实现定义的方式转换为一系列打印字符。
p The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner.
使用不正确的格式说明符是 未定义行为 。不需要不需要编译器即可针对未定义的行为生成任何诊断信息。因此,gcc和clang都是正确的。
Using incorrect format specifier is undefined behavior. A compiler is not required to produce any diagnostics for undefined behaviors. So both are gcc and clang are correct.
GCC 5.1确实会在系统上生成警告,而没有任何其他
选项。而GCC godbolt会使用更严格的编译器选项生成警告: -Wall -Wextra
。通常,应该使用最严格的编译器选项进行编译。
GCC 5.1 does produce warnings on my system without any additional
options. And GCC godbolt produces warnings with stricter compiler options: -Wall -Wextra
. In general, you should compile with strictest compiler options.
这篇关于编译器在打印变量地址时发出警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!