C++程序在迭代到数组的最后一个元素时崩溃
C++ program crashes on iterating till the last element of an array
我有以下代码:
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个整数组成的数组!索引是0
、1
、2
、3
、4
。
原因是元素在内存中的生活方式。该索引告诉您从数组开头跳出多少个点。所以第一个元素,你必须跳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';
}
}
(另外,请参阅此处了解您正在犯的一些常见的初学者错误)。
相关文章:
- lower_bound()返回最后一个元素
- 使用运算符 [] 引用 std::vector 上最后一个元素时出现问题<>
- Lower_bound不适用于具有 3 个元素的向量的最后一个元素
- 仅显示链表的最后一个元素
- push_back通过自行创建的对象获取最后一个元素的向量
- 使用 map.end() 访问 map 的最后一个元素
- 如何知道地图中的最后一个元素是否被删除?
- std::矢量保存 只推送最后一个元素
- 反转后不返回最后一个元素
- 如何在新数组较小时创建新数组并将旧数组的最后一个元素复制到新数组中?
- 在 QListView 中显示最后一个元素
- C++:在进行切片时对迭代器的约定,特别是对于访问最后一个元素并最终将其删除
- 遍历列表包含排除最后一个元素的内容
- 如何打印第一个和最后一个元素的和,然后打印第二个和倒数第二个元素的总和,依此类推
- C++链表最后一个元素的迭代器?
- 这种获取模板参数包中最后一个元素的方法是否有隐藏的开销?
- 使用 STL 交换堆栈 C++ 中的第一个和最后一个元素
- 数组:如何在指定索引之前显示数组的第一个和最后一个元素以及数组元素的差异?
- 你能pop_back一个向量,并且仍然使用迭代器到最后一个元素吗?
- 如何使用第一个、中间和最后一个元素的中位数正确分区?