警告:格式“%u”需要“unsigned int”类型的参数,但参数 2 的类型为“int*”[-Wformat=]

问题描述

当我在 GCC 编译器中编译这个简单的程序时,我收到了这个错误:- 警告:格式‘%u’需要‘unsigned int’类型的参数,但参数2的类型为‘int’ [-Wformat=]*

#include <stdio.h>
int main()
{
    printf("Pointer\n");
    printf("*******\n\n");
    int i=3;
    printf("Address of Variable i : %u",&i);
    printf("Value stored in Variable i : %d\n",i);
    printf("Value stored in Variable i : %d\n",*(&i));
    return 0;
}

解决方法

即使没有任何额外的选项,gcc (9.3.0) 也会显示详细的警告信息

a.cpp: In function 'int main()':
a.cpp:7:38: warning: format '%u' expects argument of type 'unsigned int',but argument 2 has type 'int*' [-Wformat=]
    7 |     printf("Address of Variable i : %u",&i);
      |                                     ~^  ~~
      |                                      |  |
      |                                      |  int*
      |                                      unsigned int
      |                                     %n

因此格式 %u(无符号整数)和参数 &i(指针)之间存在不匹配。

查看 printf 转换说明符

u无符号整数 转换为十进制表示形式 dddd。
...
p 编写一个实现定义的字符序列,定义一个指针

在这种情况下,指针参数 %p 的正确格式是 &i

printf("Address of Variable i : %p",&i);