当我编译以下代码时,Visual Studio 显示 C4477 警告。为什么 visual studio 会生成此警告?我该如何修复此代码?
警告:警告 C4477:“printf”:格式字符串“%d”需要“int”类型的参数,但可变参数 1 的类型为“int *”
#include <stdio.h>
int main(void) {
int num = 0;
int *pi = #
printf("Address of num: %d Value: %d\n", &num, num);
printf("Address of pi: %d Value: %d\n", &pi, pi);
return 0x0;
}
最佳答案
因为您使用的格式说明符不正确。 %d
是打印一个int
。要打印指针,请使用 %p
并转换为 void*
:
printf("Address of num: %p Value: %d\n", (void*)&num, num);
printf("Address of pi: %p Value: %p\n", (void*)&pi, (void*)pi);
转换为 void*
是必需的,因为可变参数函数不会按照要求进行从 type *
到 void *
的任何类型转换%p
。引用标准:
7.21.6 格式化输入/输出函数(C11 草案)
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.
关于c - Visual Studio 2015 中的警告 C4477,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34534852/