为什么 sscanf 不能与 bool 类型一起正常工作 [英] Why does sscanf not work properly with a bool type

查看:53
本文介绍了为什么 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.

这篇关于为什么 sscanf 不能与 bool 类型一起正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆