简体   繁体   English

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

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

I have the following code:我有以下代码:

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;
    }
}

The program is supposed to take 6 integers as input and just print them to the output.该程序应该将 6 个整数作为输入并将它们打印到输出。 It works fine for the first five integers but crashes while printing the sixth.它适用于前五个整数,但在打印第六个整数时崩溃。 As far as I know, in c++ an array defined "a[5]" should have 6 elements since it starts from 0, right?据我所知,在 C++ 中,定义为“a[5]”的数组应该有 6 个元素,因为它从 0 开始,对吗? What's causing the crash?什么原因导致崩溃?

int a[5];

is an array of 5 integers!是一个包含5 个整数的数组! The indexing is 0 , 1 , 2 , 3 , 4 .索引0 , 1 , 2 , 3 , 4

The reason for this is how the elements live in memory.原因是元素如何在内存中存活。 The index tells you how many spots to jump from the start of the array.索引告诉您从数组的开头跳出多少个点。 So the first element, you have to jump 0 spaces, because it is at the very front of the array.所以第一个元素,你必须跳0个空格,因为它在数组的最前面。 The second element, you have to jump 1 space.第二个元素,你要跳1个空格。 Get it?得到它?

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

So by trying to jump into a position that doesn't actually exist in the array, you cause Undefined Behaviour .因此,通过尝试跳转到数组中实际不存在的位置,会导致Undefined Behavior This means your program is garbage.这意味着你的程序是垃圾。 There is no guarantee at all what might happen.根本无法保证会发生什么。 It might crash, or worse, it might appear to work, because you actually hit some memory that is really being used to store a completely different object.它可能会崩溃,或者更糟的是,它可能看起来有效,因为您实际上访问了一些真正用于存储完全不同对象的内存。 Then you end up with some really crazy behaviour that is hard to debug.然后你最终会遇到一些很难调试的非常疯狂的行为。

A loop over an array should look like this:数组上的循环应如下所示:

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

But it is better to use std::vector , which will grow to the size you need, and manage all the memory for you.但最好使用std::vector ,它会增长到您需要的大小,并为您管理所有内存。 Then you can use myVector.at(3);然后你可以使用myVector.at(3); to access the data, and it will throw an exception if you make a mistake like you did above.访问数据,如果你像上面那样犯了错误,它会抛出异常。 Or better, use the "range-based for loop", which will pull out all the elements for you:或者更好的是,使用“基于范围的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';
    }
}

(Also, see here for some common beginner mistakes you are making). (此外, 请参阅此处了解您正在犯的一些常见的初学者错误)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM