c - 想要在不将数据类型更改为 char 的情况下删除警告

标签 c scanf compiler-warnings

我想在不将数据类型更改为 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: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘unsigned char *’ [-Wformat=] scanf("%d",&ch);

最佳答案

其实,

scanf("%d",&ch);

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

scanf("%hhu",&ch);

引用 C11,章节 §7.21.6.2

hh

Specifies that a following d, i, o, u, x, X, or n conversion specifier applies to an argument with type pointer to signed char or unsigned char.

关于c - 想要在不将数据类型更改为 char 的情况下删除警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42802743/

相关文章:

c - 在 C 的同一行中读取字符串和各种整数

compiler-errors - D中有一种静态打印吗?

c - malloc 有效,cudaHostAlloc 段错误?

c - 如何使用 fscanf 跳过文件中的内容?

c - 高效地乘以 7

c - 在 C 中,什么是 "%n"?这段代码是如何工作的?

c - 为什么这段代码中没有违反序列点规则?

rust - 如何抑制源自宏的Clippy警告?

在 C 中的线程内定期调用函数

c - 为什么海湾合作委员会不喜欢这样?