gpt4 book ai didi

c - 如何删除将 char 数组转换为 unsigned char 数组的警告

转载 作者:太空狗 更新时间:2023-10-29 12:01:51 24 4
gpt4 key购买 nike

你好我在Linux平台下用c编写了如下代码

#include <stdio.h>
#include <string.h>

int main(void) {
unsigned char client_id[8];
char id[17] = "00000001";
sscanf(id,"%02X%02X%02X%02X", &client_id[0], &client_id[1], &client_id[2], &client_id[3]);
printf("%02X%02X%02X%02X", client_id[0], client_id[1], client_id[2], client_id[3]);
}

当我运行这段代码时,我得到了输出

00000001

但有以下警告

> test.c: In function ‘main’: test.c:7:1: warning: format ‘%X’ expects
> argument of type ‘unsigned int *’, but argument 3 has type ‘unsigned
> char *’ [-Wformat=]
> sscanf(id,"%02X%02X%02X%02X",&client_id[0],&client_id[1],&client_id[2],&client_id[3]);
> ^ test.c:7:1: warning: format ‘%X’ expects argument of type ‘unsigned
> int *’, but argument 4 has type ‘unsigned char *’ [-Wformat=]
> test.c:7:1: warning: format ‘%X’ expects argument of type ‘unsigned
> int *’, but argument 5 has type ‘unsigned char *’ [-Wformat=]
> test.c:7:1: warning: format ‘%X’ expects argument of type ‘unsigned
> int *’, but argument 6 has type ‘unsigned char *’ [-Wformat=]

警告很明显,但我该如何删除它们?

我不想用

-Wno-pointer-sign

我应该使用 sprintf 还是对 sscanf 进行任何更改?

最佳答案

您需要告诉 sscanf 参数是 char 类型。这是通过将 hh 修饰符放在 X 格式说明符之前来完成的:

sscanf(id,"%02hhX%02hhX%02hhX%02hhX",&client_id[0],&client_id[1],&client_id[2],&client_id[3]);

关于c - 如何删除将 char 数组转换为 unsigned char 数组的警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32337543/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com