如何在函数中分配二维数组
How to allocate 2D array in a function
我有一个这样的函数:
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++ 中分配布尔值的动态二维数组时超出内存限制
- 尝试从动态分配的二维数组 C++ 中读取值时出现分段错误,并在尝试删除它时给出 munmap_chunk():
- 在 C++ 中交叉动态分配的二维数组时的侵入性值/地址
- 如何将 50 行和 50 列的二维数组编码为一个为元素随机分配星号的函数?
- 程序终止,状态为 -1073741510 在 for 循环的中间,将输入分配给二维数组
- 为什么这个指针到指针的二维数组像这样分配新的 int
- 如何在C++中动态分配连续的二维数组?
- C 从嵌套循环中的文件中读取,并将值分配给二维数组
- 动态分配缓冲空间为二维数组 - 为什么失败
- 二维数组中的动态内存分配
- 从命令行输入分配二维数组
- 如何分配两个二维数组
- 二维数组分配中的内存管理
- 二维数组和分配对象
- 二维数组C++的动态分配
- 正确分配和取消分配指向对象的指针的二维数组
- 如何在C++中动态分配全局二维数组
- 如何在函数中分配二维数组
- 如何动态分配二维数组一行在一个时间,列是已知的在c/c++