如何在函数中分配2D数组

时间:2013-05-21 20:38:59

标签: c++

我有这样的功能:

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 );

这里有什么问题?

1 个答案:

答案 0 :(得分:5)

您有运营商优先级问题 - 更改:

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

为:

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