C中的scanf字符串-为什么我可以扫描除char []声明之外的内容? [英] scanf string in c - why can i scan more than the char[] declaration?
问题描述
我有一个程序需要扫描一个字符串,我知道它只有2个字符长。 (例如: ex)。
这样做的正确方法是什么?
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 $ c格式字符串中为转换说明符
%s
指定最大字段宽度$ c>。
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屋!