c中的scanf字符串 - 为什么我可以扫描比char []声明更多的内容? [英] scanf string in c - why can i scan more than the char[] declaration?

查看:12
本文介绍了c中的scanf字符串 - 为什么我可以扫描比char []声明更多的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序需要扫描一个字符串,我知道它只有 2 个字符长.(例如:前").这样做的正确方法是什么?

I have a program where I need to scanf a string, which I know it will be only 2 characters long. (for example: "ex"). what is the proper way to do that?

我要去:

char myStr[3];
scanf("%s", myStr);

它工作得很好,但是当我输入一个 10 个字母的单词时,它也工作得很好.怎么来的?[3] 没有意义吗?我应该如何以正确的方式做到这一点?

It works just fine, but when I enter a 10-letter word it also works just fine. How come? Does the [3] has no meaning? How should I do this the proper way?

谢谢.

推荐答案

它工作得很好,但是当我输入一个 10 个字母的单词时,它也能工作很好.

It works just fine, but when I enter a 10-letter word it also works just fine.

它只是看起来工作正常,但实际上是未定义的行为.这是因为 scanf 将从 stdin 读取的字符存储到 myStr 指向的缓冲区中.myStr 的大小为 3.因此,只有 2 个字符的空间.为终止空字节节省一个字符空间,以标记由 scanf 自动添加的字符串的结尾.当输入字符串长于 2 个字符时,scanf 会超出访问数组边界内存的缓冲区.访问数组边界外的内存并调用未定义的行为是非法的.

It only appears to work fine but it's actually undefined behaviour. That is because scanf stores the characters it reads from stdin into the buffer pointed to by myStr. The size of myStr is 3. Therefore, there's space for only 2 characters. One character space is saved for the terminating null byte to mark the end of the string which is added by scanf automatically. When the input string is longer than 2 characters, scanf overruns the buffer accessing memory out of the bound of the array. It is illegal to access memory out of the array bound and invokes undefined behaviour.

下一次,它很可能会崩溃.这是不可预测的,您应该始终避免它.为了防止它,您应该在 scanf 的格式字符串中为转换说明符 %s 指定最大字段宽度.它应该比数组大小小一以容纳终止的空字节.

The next time, it may very well crash. It's unpredictable and you should always avoid it. To guard against it, you should specify maximum field width for the conversion specifier %s in the format string of scanf. It should be one less than the array size to accommodate the terminating null byte.

 char myStr[3];
 scanf("%2s", myStr);

更好的是,我建议你使用 fgets.

Better still, I suggest you to use fgets.

char myStr[3];
// read and store at most one less than 
// sizeof(myStr) chars
fgets(myStr, sizeof myStr, stdin);

这篇关于c中的scanf字符串 - 为什么我可以扫描比char []声明更多的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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