【问题标题】:what does mean this exception ? format %d expects argument of type 'int', but argument 2 has type 'long long unsigned int' [-Wformat] [duplicate]这个例外是什么意思?格式 %d 需要“int”类型的参数,但参数 2 的类型为“long long unsigned int”[-Wformat] [重复]
【发布时间】:2021-05-12 08:57:43
【问题描述】:

我是一名尝试学习 C 和 C++ 的学生,我的说明符有问题 %d 我不明白控制台中写的异常,它正在写

The format %d expects argument of type 'int', but argument 2 has type 'long long unsigned int' [-Wformat]

代码如下:

#include<stdio.h>
#include<stdlib.h>

int main()
{
    short int u=1;
    int v=2;
    long int w=3;
    char x='x';
    float y=4;
    double z=5;
    long double a=6;
    long b=7;
    printf("short int:%d\n",sizeof(u));
    printf("int:%d octets\n",sizeof(v));
    printf("long int:%d octets\n",sizeof(w));
    printf("char:%d octets\n",sizeof(x));
    printf("float:%d octets\n",sizeof(y));
    printf("double:%d octets\n",sizeof(z));
    printf("long double:%d octets\n",sizeof(a));
    printf("long:%d octets\n",sizeof(b));
    return 0;
}

【问题讨论】:

  • sizeof 的结果是size_t 类型,在您的系统上相当于 Long Long Unsigned。您应该使用%zu 而不是%d,它适用于size_t 类型的参数。

标签: c printf sizeof size-t conversion-specifier


【解决方案1】:

运算符sizeof返回的值的类型是无符号整数类型size_t转换说明符d用于输出int类型的值。您必须使用转换说明符zu。否则你会得到未定义的行为。

例如

printf("short int:%zu\n",sizeof(u));

来自 C 标准(7.21.6.1 fprintf 函数)

9 如果转换规范无效,则行为是 undefined.275) 如果任何参数不是正确的类型 相应的转换规范,行为未定义。

【讨论】:

    【解决方案2】:

    sizeof operator 返回 size_t 类型。这始终是未签名的,并且在您的平台上是long long unsigned int;在其他平台上,它可能只是 unsigned long 或者实际上是其他一些(无符号)整数类型。

    对这种类型的参数使用%zu 格式说明符;这将起作用无论实际的size_t 类型定义恰好是。

    【讨论】:

      猜你喜欢
      • 2014-02-03
      • 2015-02-27
      • 2014-01-02
      • 1970-01-01
      • 1970-01-01
      • 2021-06-22
      • 2012-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多