Home > Mobile >  Function to delete dynamically allocated 2D array
Function to delete dynamically allocated 2D array

Time:03-03

Quick question here. Using this func to allocate memory for an arr:

int **createDynamicNumArray() {
int size;
cout << "Enter size: " << endl;
cin >> size;
int **numArr = new int *[size];
for (int i = 0; i < size;   i) {
    numArr[i] = new int[size];
}
return numArr;
}

Is this the correct way for a function to clear said memory?:

void delArr(int **&numArr, int size) {
for (int i = 0; i < size;   i) {
    delete[] numArr[i];
}
delete[] numArr;
}

Key note: Do I pass just a double pointer or a double pointer reference to the function for deleting?

Thank you in advance

CodePudding user response:

Is this the correct way for a function to clear said memory?:

Yes.

Key note: Do I pass just a double pointer or a double pointer reference to the function for deleting?

Both work. I recommend not using a reference since that will be less confusing to the reader.


However, I recommend avoiding owning bare pointers in the first place. In this case, std::vector<std::vector<int>> could be appropriate.

Or, more efficient (probably; depends on how you intend to use it) alternative would be to use a single dimensional vector and translate the indices.

  • Related