为什么 sscanf 不能与 bool 类型一起正常工作

编程入门 行业动态 更新时间:2024-10-26 17:34:47
本文介绍了为什么 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 类型一起正常工作

本文发布于:2023-10-30 18:52:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1543705.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:能与   类型   工作   sscanf   bool

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!