我正在尝试分配一个大型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,但是我无法使其正常工作。任何帮助将不胜感激。

最佳答案

您是否已在调试器中运行此程序?在我看来,代码看起来不错,但是调试器会告诉您崩溃的地方,仅此一项就可以帮助您修复它

10-05 21:15
查看更多