在 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/