#include <stdio.h>
int main()
{
int arr[5], size, i, pos, elem;
printf("Enter the size of array(less than 100)\n");
scanf("%d",&size);
printf("\nEnter the elements of array one by one\n");
for ( i = 0; i < size; i++)
scanf("%d",&arr[i]);
printf("\nEnter the position of insertion\n");
scanf("%d",&pos);
printf("\nEnter the element\n");
scanf("%d",&elem);
for ( i = size - 1 ; i >= pos - 1; i--)
arr[i + 1] = arr[i];
arr[pos - 1] = elem;
printf("\nInserted array is\n");
for ( i = 0; i <= size; i++)
printf("\t%d",arr[i]);
printf("\n");
return 0;
}
由于数组是 int arr[5] ,因此不可能在 [0,1,2,3,4] 范围之外的任何索引处插入元素。为什么我能够在 arr[6] 处插入并仍然得到正确答案?
最佳答案
越界访问数组会导致未定义的行为。
您可能会看到它有时工作,有时可能不工作。(您甚至可能会崩溃)
所以只要遵循标准并停止越界访问数组即可。 摆脱未定义的行为
关于c - 一维数组的插入算法,这里发生了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28518354/