gpt4 book ai didi

c++ - 如何在函数中分配二维数组

转载 作者:搜寻专家 更新时间:2023-10-31 00:39:11 25 4
gpt4 key购买 nike

我有这样一个函数:

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;

关于c++ - 如何在函数中分配二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16679086/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com