c - 一维数组的插入算法,这里发生了什么?

标签 c arrays algorithm data-structures

#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/

相关文章:

c - 如何在 eclipse 中重命名(重构)c 宏

c++ - 是否可以只对程序的一部分使用 Boehm 垃圾收集器?

javascript - 将多个项目插入类实例内的数组中

javascript - 如何发布数组多维 Angular js

arrays - 定义派生类型数组

algorithm - 有没有渐近符号的替代方法?

c - 未知的 CMake 命令 ADD_TESH_FACTORIES

c - 使用 libcurl 监控网络状态

algorithm - 时间复杂度是多少?

java - 这个骑士之旅的算法如何修复?