C++段错误数组

标签 c++

在 C++ 中,我在告诉程序数组应该有多大 (x) 后遇到段错误。

为什么会发生这种情况,我该如何解决?

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

最佳答案

你的循环条件是错误的。

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

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

不会停在数组的末尾,因为遍历数组时条件j (i) 为真(即为假,指针需要为 nullptr)。事实上,pointer arithmetic past the array boundary plus one results in undefined behaviour .你的停止条件应该是

i < array + x;

此外,可变长度数组是一种扩展,C++ 标准不支持它。正如@Joshua Byer 指出的那样,使用 new[] 来分配内存。

关于C++段错误数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30089167/

相关文章:

c++ - 使用 union 推迟成员变量构造

c++ - 通过引用传递指针(插入二叉搜索树)

c++ - RCPP 'candidate function has different number of parameters (expected 0 but has 1)'

c++ - SFINAE 不适用于 Visual Studio 2010 for std::is_pointer

c++ - 读取 system() 命令错误响应消息

c++ - 如何在 Visual C++ 2010 Express 中更改编译器

c++ - 在 fastcgi 应用程序中访问环境变量

c++ - 使用标准算法从容器中移除对象

c++ - 将负文字作为无符号参数传递时,g++ 会发出警告吗?

c++ - Qt:我应该如何动态地将信号路由到适当的对象?