【发布时间】:2020-10-14 13:32:53
【问题描述】:
我想使用指针动态分配然后解除分配二维数组。 我的想法是创建一个指向指针数组的指针,其中每个指针都指向一个 int,这就是我想做的方式。 这些函数是 bool 类型,因为无论操作是否成功,我都想返回一个布尔值。
问题是deallocateTwoDimTable 函数不返回布尔值,所以它似乎根本不起作用。如果我不使用int** table = nullptr; 但未初始化int** table,那么我会收到错误消息(释放时),我想要释放的内存尚未初始化。
如果我将参数int **table 更改为int **&table,代码确实有效,但我猜这意味着通过引用而不是使用指针传递。我如何使它工作?非常感谢所有帮助:)
这是我的主要方法:
int main() {
int** table = nullptr;
int sizeX = 5; // rows
int sizeY = 3; // columns
bool allocationResult = allocateTwoDimTable(table, sizeX, sizeY);
cout << endl << "allocation result: " << (allocationResult ? "true" : "false") << endl;
bool deallocationResult = deallocateTwoDimTable(table, sizeX);
cout << endl << "deallocation result: " << (deallocationResult ? "true" : "false");
}
分配函数:
bool allocateTwoDimTable(int **table, int sizeX, int sizeY) {
if (sizeX <= 0 || sizeY <= 0) return false;
// allocate 2D table
table = new int*[sizeX];
for(int i = 0; i < sizeX; i++) {
table[i] = new int[sizeY];
}
cout << endl << "Table " << sizeX << " x " << sizeY << endl;
for(int i = 0; i < sizeX; i++) {
cout << endl;
for(int j = 0; j < sizeY; j++) {
cout << table[i][j] << ", ";
}
}
return true;
}
释放函数:
bool deallocateTwoDimTable(int **table, int sizeX) {
if(sizeX <= 0) return false;
for (int k = 0; k < sizeX; k++) {
delete[] table[k];
}
delete[] table;
return true;
}
【问题讨论】:
-
如果你在
table = new int*[sizeX];这样的函数中设置table,你必须通过引用传递,否则你只会设置一个副本,函数结束后会丢失。 -
为数组之类的东西分配内存的最佳方法是使用
std::vector。在销毁向量时它们更安全,事实上,如果您自己分配内存,您还应该确保在销毁指针之前自己释放内存。你可以使用std::vector中的函数push_back。 -
您的
table数组的元素未初始化。在为这些元素分配值之前,您可能不会尝试从其元素中读取(例如使用cout << table[i][j])。 -
A complete example。此外,请阅读 cmets,了解为什么您的方法(即使您让其发挥作用)存在缺陷。
-
"但我猜这意味着通过引用而不是使用指针传递" 即使它们是通过引用传递的,它仍然会使用指针。它只是对指针的引用。