在下面的代码中,我在数组中插入了 6 个元素。然而,数组大小为 5,for 循环运行 7 次。然后代码插入并打印 7 个元素。
数组的大小似乎并不重要,因为我显然可以插入和打印更多元素。如果是这样的话,那为什么还要声明数组的大小呢?
#include<stdio.h>
#include<stdlib.h>
int main()
{
int index, block[5], number;
printf("\nEnter number of elements which you want to append :");
scanf("%d", &number);
printf("\nEnter the values :");
for (index = 0; index <= number; index++)
{
scanf("%d", &block[index]);
}
for (index = 0; index <= number; index++)
{
printf("%d\t", block[index]);
}
return (0);
}
输出:
Enter the values :1
2
3
4
5
6
7
1 2 3 4 5 6 7
最佳答案
C语言有undefined behavior的概念。这意味着该语言不会阻止您做不应该做的事情,但如果您这样做,则无法保证程序随后会做什么。
它可能会崩溃,可能会输出奇怪的结果,或者可能看起来工作正常。如果您进行看似不相关的代码更改,例如添加未使用的局部变量、添加 printf
调用以进行调试或使用不同的优化设置进行编译,则未定义行为的表现方式可能会发生变化。
在这种情况下,你很“幸运”,似乎没有发生什么不好的事情。运行相同程序的其他人可能会得到与您不同的输出,因为您写的内容超出了数组的末尾。
当我运行此代码时,我得到以下输出:
Enter number of elements which you want to append :6
Enter the values :1
2
3
4
5
6
7
*** stack smashing detected ***: ./x1 terminated
1 2 3 4 5 6 7 Aborted (core dumped)
关于c - 为什么我们可以在数组中插入比数组所能容纳的更多的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51841051/