【问题标题】:Want to remove warning without change data-type to char想要删除警告而不将数据类型更改为 char
【发布时间】:2017-08-05 18:39:57
【问题描述】:

我想删除警告而不将数据类型更改为 char。

#include<stdio.h>
#include<stdlib.h>
main()
{
    unsigned char ch;
    printf("Hello This is Problematic\n");
    scanf("%d",&ch);
    printf("1\n");
}

这会产生警告

test.c:7:2: 警告:格式 '%d' 需要类型为 'int *' 的参数,但参数 2 的类型为 'unsigned char *' [-Wformat=] scanf("%d",&ch );

【问题讨论】:

  • 你想达到什么目的?这是关于您的程序中存在严重错误的警告。程序的整个行为是未定义的。
  • %d --> "%hhu" or %c, main() --> int main(void)
  • scanf 到 int,然后检查长度并复制到 char

标签: c scanf compiler-warnings


【解决方案1】:

其实

scanf("%d",&ch);

使用undefined behavior 离开您的程序,因为提供的参数不是转换说明符的正确类型。你需要写

scanf("%hhu",&ch);

引用C11,第 7.21.6.2 章

hh

指定以下 diouxXn 转换说明符适用 指向具有指向signed charunsigned char 的类型指针的参数。

【讨论】:

    猜你喜欢
    • 2013-05-10
    • 2018-11-03
    • 2017-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多