删除动态分配的二维数组的函数
在这里快速提问。使用此函数为 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;
}
:要点:我是否仅将双指针或双指针引用传递给函数进行删除?
先感谢您
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的。
两者都有效。我建议不要使用参考,因为这样不会让读者感到困惑。
但是,我建议首先避免拥有裸指针。在这种情况下,
std::vector>
可能是合适的。或者,更有效的(可能;取决于您打算如何使用它)替代方案是使用单维向量并转换索引。
Yes.
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.