【发布时间】:2009-03-12 06:25:59
【问题描述】:
我正在尝试分配一个大型 4D 矩阵,但我想动态分配。当我刚刚创建静态矩阵时,一切正常,所以我知道我现在有足够的内存。但是,当我尝试动态实现相同的东西时,每当我进入第三个维度并且我需要进入第四个维度时,它就会中断!谁能告诉我为什么这段代码不起作用?
#include <iostream>
using namespace std;
static const int time1 = 7;
static const int tlat = 15;
static const int tlon = 17;
static const int outlev = 3;
int main(void)
{
//allocate four dimensional dataIn
int ****dataIn;
dataIn = new int ***[time1];
if (dataIn == NULL) { return 1; }
for(int i = 0 ; i < time1 ; i++) {
dataIn[i] = new int **[tlat];
if (dataIn[i] == NULL) { return 1; }
for(int j = 0 ; j < tlat ; j++) {
dataIn[i][j] = new int *[tlon];
if (dataIn[i][j] == NULL) { return 1; }
for(int k = 0 ; k < tlon ; k++) {
dataIn[i][j][k] = new int[outlev];
if (dataIn[i][j][k] == NULL) { return 1; }
}
}
}
//there is more code that happens here to add values to dataIn
//and eventually output it but I know all of that works
return 0;
}
我在这段代码上尝试了许多不同的变体,甚至使用 malloc 代替 new,但我无法让它工作。任何帮助将不胜感激。
【问题讨论】:
-
这里不会崩溃。也许实际代码块会有所帮助。
-
我编译了您发布的代码,它在 VS2005 中运行而没有崩溃。请更具体地说明您的问题。
-
在下面的评论中,您指出错误在线:'dataIn[i][j] ='。 i 和 j 的值是多少。返回的指针的值是多少等。如果您没有调试器(难以理解),那么您可以通过放置显示状态的打印语句来以老式方式进行。
标签: c++ dynamic matrix segmentation-fault