我刚刚开始使用十六进制值(用 C 语言),下面是代码:
int main(){
unsigned char x, y, z;
scanf("%x", &x);
scanf("%x", &y);
scanf("%x", &z);
printf("val are: %x, %x, %x\n",x,y,z);
return 0
}
在上面的代码中,为什么x
和y
的值丢失/被覆盖,如何解决?
最佳答案
引用 C11
,第 §7.21.6.2 章,对于 %x
转换说明符,(__emphasis mine_)
x
Matches an optionally signed hexadecimal integer, whose format is the same as expected for the subject sequence of the
strtoul
function with the value 16 for the base argument. The corresponding argument shall be a pointer to unsigned integer.
您将参数作为指向无符号字符
的指针提供。
此外,来自同一章,P10
[...] Unless assignment suppression was indicated by a
*
, the result of the conversion is placed in the object pointed to by the first argument following the format argument that has not already received a conversion result. If this object does not have an appropriate type, or if the result of the conversion cannot be represented in the object, the behavior is undefined.
因此,您的代码会调用未定义的行为。
如果参数是指向 unsigned char
的指针,则需要使用格式说明符 %hhx
。
关于c - 在多个 unsigned char 变量中输入十六进制值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58973513/