如何在函数中分配二维数组

How to allocate 2D array in a function

本文关键字:分配 二维数组 函数      更新时间:2023-10-16

我有一个这样的函数:

void QuadTree::alloc( Quad***& pQuadsArray ) {
    const int _quadsCount = 100;
    // allocates memory as one chunk of memory
    Quad** _data = new Quad*[_quadsCount * _quadsCount]; 
    pQuadsArray = new Quad**[_quadsCount];
    for( int i = 0; i < _quadsCount; ++i ) {
            pQuadsArray[i] = _data + i * _quadsCount;
    }
}
// calling like this:
Quad*** test = nullptr;
alloc( test );

效果很好。但是这个没有,我不知道为什么:

void QuadTree::alloc( Quad**** pQuadsArray ) {
    const int _quadsCount = 100;
    // allocates memory as one chunk of memory
    Quad** _data = new Quad*[_quadsCount * _quadsCount]; 
    *pQuadsArray = new Quad**[_quadsCount];
    for( int i = 0; i < _quadsCount; ++i ) {
            *pQuadsArray[i] = _data + i * _quadsCount; // code crashes here
            // tried *(pQuadsArray[i]) but it didn't help
    }
}
// calling like this:
Quad*** test = nullptr;
alloc( &test );

怎么了?

操作符优先级问题-更改:

        *pQuadsArray[i] = _data + i * _quadsCount; // code crashes here

:

        (*pQuadsArray)[i] = _data + i * _quadsCount;