为什么 sscanf 不能与 bool 类型一起正常工作
这段代码的输出:
const char *buff = "*_2D 1";
char field[10];
int flag;
sscanf(buff, "%s %d", field, &flag);
printf("field:%s flag:%i
", field, flag);
是 field:*_2D flag:1
但是,将 int
更改为 bool
会导致奇怪的行为:
However by changing the int
to bool
results in strange behaviour:
const char *buff = "*_2D 1";
char field[10];
bool flag;
sscanf(buff, "%s %d", field, &flag);
printf("field:%s flag:%i
", field, flag);
输出是 field: flag:1
谁能解释这里发生了什么?我原以为 bool 会被解释为一个 int,它似乎是,但字符串的其余部分消失了.
Can anyone explain what is happening here? I would've thought the bool would be interpreted as an int, which it appears to be, but the rest of the string disappears.
推荐答案
想象一下,如果 bool
只有一个字节,而不是 int
用途.然后告诉 sscanf
&flag
是一个指向 int
的指针,最终会覆盖堆栈上其他地方的三个或七个字节――这可能就在您的 field
变量之上.该空间将被 0 个字节填充,有效地终止您的字符串.
Imagine if bool
is only one byte, rather than the four (or even eight) that an int
uses. Then telling sscanf
that &flag
is a pointer to an int
will end up overwriting either three or seven bytes elsewhere on the stack -- which could be right on top of your field
variable. That space would be filled with 0 bytes, effectively terminating your string.
相关文章