如何删除char数组中转换为unsigned char数组的警告

时间:2015-09-01 17:25:26

标签: c linux types casting char

您好我在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指针-符号

我应该使用sprintfsscanf中的任何更改吗?

1 个答案:

答案 0 :(得分:3)

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

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