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

4
  • 1
    FWIW, if you use a std::vector<std::vector<int>> numArr(size, std::vector<int>(size)) you don't need to worry about cleaning anything up. Commented Mar 2, 2022 at 20:49
  • X-Y answer Commented Mar 2, 2022 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. Commented Mar 2, 2022 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. Commented Mar 2, 2022 at 20:53

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.