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

为何下述C语言代码输出的数组元素数量超过6个?

问题分析:C语言数组插入元素后出现垃圾值的原因

原代码

#include <stdio.h>

int main() {
    int a[] = {10, 20, 30, 40, 50};
    int size = sizeof(a) / sizeof(a[0]);
    int num, pos;
    printf("Enter the number to insert in the array: ");
    scanf("%d", &num);
    printf("Enter the position to enter the element in the array: ");
    scanf("%d", &pos);

    if (pos < 0 || pos > size) {
        printf("Invalid position!");
    } else {
        // Move elements to make space for the new element
        for (int i = size - 1; i >= pos; i--) {
            a[i + 1] = a[i];
        }

        // Insert the new element
        a[pos] = num;

        // Update the size of the array
        size++;

        printf("The updated array is: ");
        for (int i = 0; i < size; i++) {
            printf("%d ", a[i]);
        }
    }
    return 0;
}

问题原因

  1. 静态数组内存大小固定:代码里的数组a是栈上静态分配的数组,编译阶段就确定了它只能容纳5个int元素(合法索引范围0-4),程序运行时无法动态扩展它的内存空间。
  2. 数组越界访问:执行插入逻辑时,循环将元素向后移位(a[i+1] = a[i]),当i等于原数组最后一个索引(4)时,i+1就是5,已经超出了数组的合法内存边界,此时写入的是数组之外的栈内存区域。
  3. 逻辑大小与实际内存不匹配:代码中的size变量仅记录逻辑上的元素数量,size++只是修改了这个变量的值,并没有真正为数组分配新的内存。当循环打印到i=5时,访问的是数组内存之外的栈空间,这里的内容是程序运行过程中残留的随机垃圾数据,因此会显示无意义的乱值。

内容的提问来源于stack exchange,提问作者Sarvesh Gajendragadkar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 22:17:08