#include <stdio.h>
int main() {
char a[] = "e:a";
unsigned char c[2] = {0,};
sscanf(a,"%1x:%1x",&c[0],&c[1]);
printf("%d\n", c[0]);
printf("%d\n", c[1]);
}
我希望输出这段代码,
14
10
但是,
14
0
然而,当我更正下面的代码时,
#include <stdio.h>
int main() {
char a[] = "e1:1a";
unsigned char c[2] = {0,};
sscanf(a,"%2x:%2x",&c[0],&c[1]);
printf("%d\n", c[0]);
printf("%d\n", c[1]);
}
输出是,
30
26
它有什么问题?
答案 0 :(得分:1)
错误匹配scanf()
类型和参数。 @Tom Karzes
// bad
unsigned char c[2] = {0,};
sscanf(a,"%1x:%1x",&c[0],&c[1]);
如果转换规范无效,则行为未定义C11dr§7.21.6.213
将unsigned *
与"%x"
一起使用,或将unsigned char *
与"%hhx"
一起使用。
unsigned c[2];
sscanf(a,"%1x:%1x",&c[0],&c[1]);
// or
unsigned char c[2];
sscanf(a,"%1hhx:%1hhx",&c[0],&c[1]);
启用了警告的好编译器通常会报告此问题 - 节省时间。
很高兴检查sscanf()
结果。
if (sscanf(a,"%1x:%1x",&c[0],&c[1]) != 2) Handle_ScanFailure.