I'd like to dynamically allocate and then deallocate a 2D array using pointers. My idea is to create a pointer to an array of pointers, where each pointer points to an int and that's how I would like to do it. The functions are type of bool as I want to return a boolean whether the action was successful or not.
The problem is that deallocateTwoDimTable
function doesn't return a bool, so it seems like it doesn't work at all. If I don't use int** table = nullptr;
but leave it uninitialised int** table
, then I get the error (when deallocating) that the memory that I want to free haven't been initialised.
The code does work if I change the parameter int **table
to int **&table
, but I guess that means passing by reference instead of using pointers. How do I make it work? All the help is really appreciated :)
Here's my main method:
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");
}
Allocation function:
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;
}
Deallocation function:
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;
}