简体   繁体   English

C ++分段故障数组

[英]C++ segmentation fault array

In C++ I get a segmentation fault after telling the program how big the array should be (x). 在C ++中,我在告诉程序数组应该多大(x)之后遇到了分段错误。

Why is this happening and how do I fix this? 为什么会发生这种情况,我该如何解决?

#include <iostream>
using namespace std;

int main()
{
    int x;
    cin >> x;
    int array[x];

    for (int *j=array; j; j++)
    {
        *j=0;
    }

    for (int *i=array; i; i++)
    {
        cin >> *i;
    }

    cout << array[3] << endl;
}

Your loop conditions are wrong. 您的循环条件是错误的。

for (int *j = array; j; j++)

and

for (int *i=array; i; i++)

will not stop at the end of the array, as the condition j ( i ) is true when traversing the array (ie, to be false, the pointer needs to be nullptr ). 不会停止在数组的末尾,因为遍历数组时条件ji )为true(即,为false时,指针需要为nullptr )。 In fact, pointer arithmetic past the array boundary plus one results in undefined behaviour . 实际上, 指针算术超出数组边界加一会导致未定义的行为 Your stopping condition should be 您的停车条件应为

i < array + x;

Moreover, variable length arrays are an extension and not support by the C++ standard. 此外,可变长度数组是C ++标准的扩展,不支持。 Use new[] instead to allocate memory, as @Joshua Byer pointed out. 正如@Joshua Byer指出的那样,请使用new[]分配内存。

Within a for statement, the second expression should terminate the loop by evaluating to false . for语句中,第二个表达式应通过评估为false来终止循环。 In this case however you never terminate the loop: 但是,在这种情况下,您永远不会终止循环:

for (int *j=array; j; j++)

Instead do: 而是:

for (int *j=array; j < array + x; j++)

The expression array + x (by pointer arithmetic) means one element past the end of the array. array + x (通过指针算术)的表达式表示超出数组末尾的一个元素。

The above goes for both of the loops. 以上适用于两个循环。

The conditions used in your loops are incorrect. 循环中使用的条件不正确。

eg. 例如。 for (int *j = array; j; j++) even though j will eventually reach the end of the array but will still never evaluate to false (allowing the loop to finish). for (int *j = array; j; j++)即使j最终会到达数组的末尾,但仍然永远不会取值为false(允许循环完成)。 On top of this it means you will iterate to past the end of the array and move into Undefined Behaviour, this is probably why you are seeing the segfault. 最重要的是,这意味着您将遍历数组的末尾并进入“未定义行为”,这可能就是您看到段错误的原因。

you either need to do the following (super gross solution!!!! also not C++ standard supported): 您要么需要执行以下操作(超级总解决方案!!!!还不支持C ++标准):

for (int i = 0, *j = array; i < x; i++, j++)

which will increment a counter and check the array at the same time as incrementing your pointer. 这将增加一个计数器并在增加指针的同时检查数组。

OR USE VECTORS 使用矢量

std::vector is a much easier way to do what you are doing. std :: vector是做您正在做的事情的一种简单得多的方法。

int arraySize;
cin >> arraySize;
std::vector<int> array(arraySize, 0);

for (int i=0; i < arraySize; i++)
{
    cin >> array[i];
}

cout << array.at(3) << endl;

Here is a live example. 这是一个实时示例。

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

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