【问题标题】:How to remove warning for conversion in char array to unsigned char array如何删除将字符数组转换为无符号字符数组的警告
【发布时间】:2015-11-27 00:57:57
【问题描述】:

你好我在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 中的任何更改?

【问题讨论】:

  • unsigned int client_id[8]; 也许?

标签: c linux types casting char


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-16
    • 1970-01-01
    • 2012-05-10
    • 2014-03-18
    • 1970-01-01
    • 2013-05-06
    • 2010-10-23
    相关资源
    最近更新 更多