删除动态分配的二维数组的函数

发布于 2025-01-11 08:58:28 字数 502 浏览 2 评论 0 原文

在这里快速提问。使用此函数为 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;
}

这是函数清除所述内存的正确方法吗?

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

:要点:我是否仅将双指针或双指针引用传递给函数进行删除?

先感谢您

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

这样的小城市 2025-01-18 08:58:28

这是函数清除所述内存的正确方法吗?:

是的。

要点:我是否只向函数传递一个双指针或一个双指针引用以进行删除?

两者都有效。我建议不要使用参考,因为这样不会让读者感到困惑。


但是,我建议首先避免拥有裸指针。在这种情况下,std::vector> 可能是合适的。

或者,更有效的(可能;取决于您打算如何使用它)替代方案是使用单维向量并转换索引。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文