C++程序在迭代到数组的最后一个元素时崩溃

C++ program crashes on iterating till the last element of an array

本文关键字:最后一个 元素 崩溃 数组 程序 迭代 C++      更新时间:2023-10-16

我有以下代码:

int main()
{
int a[5];
for (int i = 0; i <= 5; i++) {
cin >> a[i];
}
for (int i = 0; i <= 5; i++) {
cout << a[i] << endl;
}
}

该程序应该将 6 个整数作为输入,然后将它们打印到输出中。它适用于前五个整数,但在打印第六个整数时崩溃。据我所知,在 c++ 中,定义"a[5]"的数组应该有 6 个元素,因为它从 0 开始,对吧?是什么导致了崩溃?

int a[5];

是一个由5个整数组成的数组!索引01234

原因是元素在内存中的生活方式。该索引告诉您从数组开头跳出多少个点。所以第一个元素,你必须跳0个空格,因为它在数组的最前面。第二个元素,你必须跳1个空格。明白了吗?

array start       |data|data|data|data|data|<nothing here!>
offset from start |   0|   1|   2|   3|   4| not allowed!!

因此,通过尝试跳转到数组中实际上不存在的位置,会导致未定义的行为。这意味着你的程序是垃圾。根本无法保证会发生什么。它可能会崩溃,或者更糟糕的是,它可能看起来有效,因为您实际上遇到了一些真正用于存储完全不同的对象的内存。然后你最终会得到一些非常疯狂的行为,很难调试。

数组上的循环应如下所示:

for (size_t i = 0; i < arraySize; ++i) // ...
^ always <, never <=

但最好使用std::vector,它将增长到您需要的大小,并为您管理所有内存。然后您可以使用myVector.at(3);来访问数据,如果您像上面那样犯了错误,它将引发异常。或者更好的是,使用"基于范围的for循环",它将为您提取所有元素:

#include <vector>
#include <iostream>
int main()
{
const std::size_t howMany = 6; // how many ints to read
std::vector<int> data;
while (data.size() < howMany) { // haven't read enough yet
int tmp = 0;
std::cin >> tmp;
if (!std::cin) { // somehow reading went wrong!
return 1; // exit the program with an error code
}
data.push_back(tmp); // store the value we just read
}
for (int i : data) { // go through all the stored ints
std::cout << i << 'n';
}
}

(另外,请参阅此处了解您正在犯的一些常见的初学者错误)。