阵列无法正确打印 C++

Array not printing Properly in C++

本文关键字:打印 C++ 阵列      更新时间:2023-10-16

运行此程序时,如果n的值设置为 10,它将打印数组a的索引和存储的值从 a[0]a[9] 。但是,如果我将 n 的值设置为 10 以上,那么它只会将数组a的索引从 a[0] 打印到 a[5] 及其存储的值。有人可以向我解释为什么会发生这种情况吗?

#include <iostream>
using namespace std;
int main()
{
    int a[10];
    int i, n=11;
    for(i=0; i<n; i++) {
        a[i]= 5;
    }
    cout<<"The array is: n";   
    for(i=0; i<n; i++)
    {
        cout<<"a["<<i<<"] = "<<a[i]<<endl;
    }
    return 0;
}
如果将

n 的值增加到数组的大小以上(或等于从 0 开始索引(,则超过数组的末尾。 超过数组的末尾是未定义的行为。 如果程序表现出未定义的行为。 任何事情都可能发生。 有关未定义行为的更多信息,请参阅Microsoft的这篇博客文章

如果您切换到 std::array 而不是 C 数组并使用 .at() ,那么会发生一些定义良好的事情,您将获得std::out_of_range异常。 有关更多信息,请参阅 http://en.cppreference.com/w/cpp/container/array/at 和 http://en.cppreference.com/w/cpp/container/array