阵列无法正确打印 C++
Array not printing Properly in C++
运行此程序时,如果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
相关文章:
- 如何循环打印顶点结构
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 如何在c++中打印目录
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 在线编译器中的分段C++没有打印消息
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 如何将结构插入到集合中并打印集合的成员
- 在循环C++中指定字符串之后,不会打印该字符串
- 以螺旋方式打印矩阵的程序.(工作不好)
- 从控制台中删除最后打印的元素
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何仅使用对象名称打印特定于对象的成员
- 回溯C++不打印函数,因此文件
- 在一定长度后从数组中打印时缺少整数
- 为什么这个 c++ 代码打印出长度 5,当我打印出字符串时,程序会自动终止?
- 在gem5中打印文件中的所有cache_blocks
- 打印数字图案
- Log4cpp:以UTC/GMT时区打印日期
- 如何使用gdb制作一个可以漂亮地打印每个对象的C++函数