以下代码在运行时抛出Segmentation fault (core dumped)
错误。代码用g ++编译
struct SomeClass {
int *available;
int **need;
int **allocation;
}
SomeClass::SomeClass(int nR, int nT) {
available = new int[nR];
for (int i = 0; i < nR; i++) {
available[i] = 1;
}
*allocation = new int[nT];
*need = new int[nT];
for (int i = 0; i < nT; i++) {
allocation[i] = new int[nR];
need[i] = new int[nR];
for (int j = 0; j < nR; j++) {
allocation[i][j] = 0;
need[i][j] = 1; // should equal 1
}
}
}
我确定此代码产生错误吗?是!因为我评论了它,一切正常。
我查了这个问题:
A segmentation fault error with 2D array
答案是设置堆栈大小ulimit -s unlimited
......但这并没有解决问题。
答案 0 :(得分:3)
因为您的类型是:
int **need;
int **allocation;
这些界限:
*allocation = new int[nT]; // dereferencing uninitialized pointer
*need = new int[nT];
应该是:
allocation = new int*[nT]; // proper allocation
need = new int*[nT];
您是否认为int*
allocation[i] = new int[nR];
类型的元素需要工作?
答案 1 :(得分:2)
我强烈建议(并强烈感受似曾相识)摆脱尝试使用指针指针模拟二维数组。很难做到这一点。将所有值打包成一维数组。