0

Why can I store more than 3 characters in the array "char array[3]" ? For example, in this code:

#include <stdio.h>

char array[3];

main()
{
scanf("%s", array);
putchar(array[5]);
return 0;
}

You can enter a text of any length, and it will print the 6th letter. You can also print the entire text with "printf("%s", array). Why does this work although the array only has space for 3 characters?

4

3 回答 3

3

您的代码能够打印整个单词,因为它还没有被覆盖。您正在设置内存,然后立即从中读取。如果您稍后在程序执行时尝试从该内存位置读取,您可能会得到完全不同的结果。

这是未定义的行为......在你的情况下,它打印了“正确”的输出。

于 2013-02-14T17:25:23.360 回答
1

array被定义为一个全局数组,因此通常是部分的.bss一部分。由于您系统的 .bss 部分有足够的内存,您可以写入相同的内容。显然,这是一种违规行为,当您超出此部分的大小时会被捕获。

于 2013-02-14T17:25:58.740 回答
0

由于 scanf() 的工作方式,它只会继续将发送给它的内容写入内存。因为您在写入后立即读取,所以数组使用的额外内存尚未被覆盖,因此您可以读取整个字符串。
C 中还有其他函数会限制您的输入,例如 fgets()。

于 2013-02-14T17:30:04.523 回答