【问题标题】:warning: format ‘%u’ expects argument of type ‘unsigned int’, but argument 2 has type ‘int*’ [-Wformat=]警告:格式“%u”需要“unsigned int”类型的参数,但参数 2 的类型为“int*”[-Wformat=]
【发布时间】:2021-06-22 23:58:16
【问题描述】:

当我在 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;
}

【问题讨论】:

  • 使用 %p 打印指针。
  • 我得到这种地址:- 变量 i 的地址:0x7ffc836a8534
  • 我想要整数类型的地址
  • 嗯,十六进制对于指针来说是常规的。这有点像 hack,但您可能会强制转换为 unsigned long 并使用 %lu 打印

标签: c++ gcc-warning


【解决方案1】:

即使没有任何额外选项,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(无符号整数)和参数&amp;i(指针)不匹配。

查看printf 转换说明符

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

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

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

【讨论】:

    猜你喜欢
    • 2015-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-03
    • 1970-01-01
    • 2011-06-12
    • 1970-01-01
    • 2019-04-03
    相关资源
    最近更新 更多