scanf无法扫描到uint8_t

当我尝试将scanfuint8_t一起使用时,我得到了疯狂的结果。 使用int ,我得到预期的输出“08 – 15”。 使用uint8_t ,我得到“00 – 15”。

 const char *foo = "0815"; uint8_t d1, d2; // output: 00 - 15 (!!!) // int d1, d2; // output: 08 - 15 sscanf(foo, "%2d %2d", &d1, &d2); printf("%02d - %02d\n", d1, d2); 

我正在使用GCC。

%d是错误的,因为这意味着你传递int *但实际上你想传递uint8_t * 。 您将需要使用适当的宏:

 #include  ... sscanf(foo, "%2" SCNu8 " %2" SCNu8, &d1, &d2); 

大多数编译器应该为您提供有关您的代码版本的警告。 这是Clang的输出:

 test2.c:8:24:warning:format指定类型'int *'但参数有类型
       'uint8_t *'(又名'unsigned char *')[ -  Wformat]
 sscanf(foo,“%2d%2d”,&d1,&d2);
              ~~~ ^ ~~
              %2秒
 test2.c:8:29:warning:format指定类型'int *'但参数有类型
       'uint8_t *'(又名'unsigned char *')[ -  Wformat]
 sscanf(foo,“%2d%2d”,&d1,&d2);
                  ~~~ ^ ~~
                  %2秒
生成2个警告。

对于uint8_t ,这不适用于printf() ,因为uint8_t在传递给printf()之前将始终被提升为int

scanf格式说明符%d表示“我保证会给你一个int * ”。 你通过不提供int的地址来打破这个承诺。 所有赌注都已关闭。 (这是未定义的行为 。)

道德:不要欺骗你的编译器。

您的代码不起作用,因为当uint8_t只有一个字节时,您告诉scanf()期望指向4字节类型(int)的指针。

 #define __USE_MINGW_ANSI_STDIO 1 //or gcc prog.c -std=c99 -D__USE_MINGW_ANSI_STDIO #include  #include  #include  int main(){ const char *foo = "0815"; uint8_t d1, d2; sscanf(foo, "%2" SCNu8 "%2" SCNu8, &d1, &d2); printf("%02" PRIu8 " - %02" PRIu8 "\n", d1, d2); return 0; }