0

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

Nik
  • 37
  • 6
  • 1
    FWIW, if you use a `std::vector> numArr(size, std::vector(size))` you don't need to worry about cleaning anything up. – NathanOliver Mar 02 '22 at 20:49
  • [X-Y answer](https://isocpp.org/wiki/faq/operator-overloading#matrix-subscript-op) – user4581301 Mar 02 '22 at 20:49
  • 1
    No need for reference in this case unless you want to change where the caller's pointer points. Just having the pointer is sufficient to delete the object at the pointer. – user4581301 Mar 02 '22 at 20:50
  • To directly answer the (first) question: Yes, that would work. But it would resemble C code, in a language that has gone to great lengths to eliminate the need for bug-prone memory micro-management like this. – Drew Dormann Mar 02 '22 at 20:53

1 Answers1

3

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.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • [Very simple example of a `std::vector`-based 1D matrix as mentioned in the last paragraph](https://stackoverflow.com/a/2076668/4581301). – user4581301 Mar 02 '22 at 20:59