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

C++数组读取打印出现垃圾值,求排查原因

问题分析与解决

你的代码出现垃圾值和异常输出的核心原因是数组下标越界以及未正确初始化数组元素,具体问题如下:

关键错误点

  • C++数组下标从0开始:数组的有效下标范围是0到size-1,但你的代码存在两处错误:
    1. 读取数组时,i从1开始,循环条件i<=number会让你访问array[number]——这属于越界访问,是未定义行为,可能破坏内存数据。
    2. 打印数组时,循环条件j<=number会多打印一个越界元素,同时array[0]从未被赋值,内存里的随机值(比如你看到的16)就会被输出。

修正后的代码

#include <iostream>
using namespace std;

int main(){
    int number;
    cout<<"Enter array size"<<endl;
    cin>>number;

    int array[number];
    // 从下标0开始读取,遍历到number-1
    int i=0;
    while(i < number){
        cin>>array[i];
        i++;
    }
    // 同样遍历有效下标范围
    int j=0;
    while(j < number){
        cout<<array[j]<<endl;
        j++;
    }
    return 0;
}

额外建议

注意:int array[number]属于编译器扩展的变长数组,并非标准C++语法。如果要编写符合标准的代码,推荐使用标准库的vector(动态数组),更安全且兼容性更好:

#include <iostream>
#include <vector>
using namespace std;

int main(){
    int number;
    cout<<"Enter array size"<<endl;
    cin>>number;

    vector<int> array(number);
    int i=0;
    while(i < number){
        cin>>array[i];
        i++;
    }
    int j=0;
    while(j < number){
        cout<<array[j]<<endl;
        j++;
    }
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 15:27:11