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

如何在C语言数组的多个不同位置插入相同元素

C语言实现数组指定位置插入元素方案

核心思路

  • 提前申请容量足够的临时缓冲区存储结果,避免数组越界
  • 双下标分别跟踪原数组遍历进度、新数组写入进度
  • 遍历原数组时遇到999先插入1000,再保留原有999,其余元素直接写入新数组

完整实现代码

#include <stdio.h>

int main() {
    // 原数组定义
    int arr[10] = {1,2,999,4,5,999,7,999,9,10};
    int arr_len = sizeof(arr) / sizeof(arr[0]);
    // 临时缓冲区,容量100足够容纳插入后的结果
    int temp[100] = {0};
    // 新数组的写入下标
    int temp_idx = 0;

    for (int i = 0; i < arr_len; i++) {
        if (arr[i] == 999) {
            // 遇到999先插1000
            temp[temp_idx++] = 1000;
        }
        // 写入原数组当前元素
        temp[temp_idx++] = arr[i];
    }

    // 打印结果验证
    printf("插入后的数组结果:\n");
    for (int i = 0; i < temp_idx; i++) {
        printf("%d ", temp[i]);
    }
    printf("\n");

    return 0;
}

运行输出

插入后的数组结果:
1 2 1000 999 4 5 1000 999 7 1000 999 9 10 

完全符合预期输出要求。如果原数组的999数量不确定,也可以先遍历一次原数组统计999的数量,用原数组长度+999数量的值作为新数组的申请长度,避免空间浪费。

内容的提问来源于stack exchange,提问作者V B

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 10:48:04