I'm trying to allocate a large 4D matrix but I want to do it dynamically. When I just create the static matrix everything works fine so I know I have enough memory for now. However when I try and implement the same thing dynamically it breaks whenever I enter the third dimension and I need to get to a fourth! Can anyone tell me why this code does not work?
#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;
}
I have tried many different variations on this code, and even used malloc instead of new, but I cannot get it working. Any help will be greatly appreciated.