You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言一维数组指定位置插入元素异常问题排查

问题根源与修复方案

你的代码存在两个核心问题,导致插入操作直接覆盖元素而非将目标位置及右侧元素右移:

1. 循环右移的条件错误

你写的循环逻辑:

for (int i = size-1; i >= position; i--)
{
    arr[i+1] = arr[i];
}

这里的position是用户输入的从1开始计数的位置,对应的数组索引是position-1。循环需要从最后一个元素(索引size-1)遍历到目标索引position-1,才能把目标位置及右侧的所有元素都向右移动一位。但你当前的循环终止条件是i >= position,直接跳过了目标索引position-1的元素,导致这个位置的元素没有被右移,直接被插入值覆盖。

正确的循环条件应该是:

for (int i = size-1; i >= position-1; i--)

2. 栈数组的空间不足(未定义行为)

creation函数里的int arr[size]是栈上分配的固定大小数组,它的内存空间只有size个int的容量。当你执行arr[i+1] = arr[i]时,若i = size-1,arr[i+1]就是arr[size],已经超出了数组的原始内存范围,属于未定义行为——栈上这个位置可能存储着其他变量的数据,写入会破坏程序的正常运行,甚至导致崩溃。

解决方法是使用动态分配的数组,通过malloc分配内存,插入元素时用realloc扩容,确保有足够空间存储新元素。

其他潜在问题

  • creation函数中传递给insertion的position和value是未初始化的垃圾值,虽然insertion里重新输入了,但这是不良编码习惯,应当避免。
  • insertion函数里的size += 1仅修改了函数内部的局部变量,无法同步外部的数组实际大小,动态分配时需要通过指针传递来更新容量。

修正后的完整代码

#include <stdio.h>
#include <stdlib.h>

void insertion(int **arr, int *size, int position, int value);

int main()
{
    int size, position, value;
    printf("Enter the size of the parent array you wish to create - ");
    scanf("%d", &size);

    // 动态分配数组内存
    int *arr = (int *)malloc(size * sizeof(int));
    if (arr == NULL) {
        printf("Memory allocation failed!\n");
        return 1;
    }

    for (int i = 0; i < size; i++)
    {
        printf("Enter the parent array element - ");
        scanf("%d", &arr[i]);
    }
    printf("Parent array created with elements \n");
    for (int i = 0; i < size; i++)
    {
        printf("%d \t", arr[i]);
    }
    printf("\n");

    insertion(&arr, &size, position, value);

    // 释放动态分配的内存
    free(arr);
    return 0;
}

void insertion(int **arr, int *size, int position, int value)
{
    printf("Enter the position in the parent array where you would like to insert the element - ");
    scanf("%d", &position);
    if (position <= 0 || position > *size + 1)
    {
        printf("Invalid position entered, cannot add element! \n");
        return;
    }

    printf("Enter the value you wish to insert - ");
    scanf("%d", &value);

    // 扩容数组
    int *new_arr = (int *)realloc(*arr, (*size + 1) * sizeof(int));
    if (new_arr == NULL) {
        printf("Memory reallocation failed!\n");
        return;
    }
    *arr = new_arr;

    // 从后往前右移元素
    for (int i = *size - 1; i >= position - 1; i--)
    {
        (*arr)[i + 1] = (*arr)[i];
    }

    // 插入新元素
    (*arr)[position - 1] = value;
    // 更新数组大小
    (*size) += 1;

    printf("Array after insertion successfully \n");
    for(int i = 0; i < *size; i++)
    {
        printf("%d \t", (*arr)[i]);
    }
    printf("\n");
}

内容的提问来源于stack exchange,提问作者Aryan Mahawar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 22:45:23