0

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.

4

5 回答 5

2

Have you run this in a debugger? To my eyes the code looks fine, but a debugger will tell you where it's crashing which alone may be enough to help you fix it

于 2009-03-12T06:36:32.713 回答
2

You're probably best off allocating all the memory in a flat array and then calculating the indices yourself. Wrapping the whole thing in an object for encapsulation.

class Matrix {
private:
        int* data;        
        int[] sizes;
        int nDimensions;

public:
        // allocates the data pointer and copies the other parameters
        Matrix(int[] sizes, int nDimensions); 

        // frees the data and sizes arrays
        ~Matrix();

        // calculates the cell position and returns it
        int getCell(int[] coordinates);

        // calcultes the cell position and sets its value
        void setCell(int[] coordinates, int value);

private:
        // used by getCell and setCell, calculates the cell's 
        // location in the data array
        size_t calculateCellPosition(int[] coordinates);
};
于 2009-03-12T06:47:18.193 回答
1

它在我的 Linux 机器上编译并运行良好。

顺便说一句,对于标准 C++,new 在无法分配内存时会抛出 std::bad_alloc 异常(而不是返回 NULL)。因此,捕获该异常而不是测试 NULL 指针可能是值得的。

于 2009-03-12T07:39:56.337 回答
0

正如 cmeerw 所指出的,在 std-c++ 中不需要针对 NULL 或 0 进行测试。

如果您可以在获得 segv 的确切位置添加评论,将会有所帮助。

另外:您使用的是哪个编译器以及在哪个操作系统上?

于 2009-03-12T08:12:46.960 回答
0

查看boost::multiarray,它完全符合您的要求,除了通过仅执行单个堆分配更有效。

于 2009-03-12T08:18:17.710 回答