披露:我正在尝试解决具有严格时间和内存限制的挑战。我通常会使用 vector 和字符串,但在这里我需要最快和最小的解决方案(使用 vector 它实际上超过了时间限制),所以我转向了 char* 的动态数组。 我的代码的相关部分:
char** substrings(string s, int* n){
*n = 0;
...
////////////////////////////////
char** strings = new char*[*n];
////////////////////////////////
for (int i = 0; i < s.length(); i++){
for (int j = 1; j < s.length() - i + 1; j++){
...
strings[si] = tmp;
...
}
}
return strings;
}
int main(){
...
for (int ti = 0; ti < t; ti++){
cin >> s;
char** substr = substrings(s, &n);
...
for (int i = 0; i < n; i++){
delete substr[i];
}
}
return 0;
}
在不删除数组的情况下,一切都运行良好,但这是 Not Acceptable ,那么我该如何处理呢?我尝试了很多看起来合乎逻辑的变体,但我遇到了运行时错误。
最佳答案
它类似于分配,但顺序相反,并且使用 delete[]
而不是 new[]
:
for(int i = 0; i < LENGTH; i++)
delete[] strings[i]; // delete each pointer in char** strings
delete[] strings; // finally delete the array of pointers
我在这里假设 LENGTH
是指向 char*
的指针数组的长度。所以看起来你只执行了第一轮解除分配
for (int i = 0; i < n; i++){
delete substr[i]; // need delete[] substr[i] here
但是使用delete
而不是delete[]
,你需要delete[] substr[i]
,因为我猜是substr[i]
是一个 char*
指针,指向 new[]
分配的 char
数组的第一个元素>。你终于需要额外的
delete[] substr;
关于c++ - 在 C++ 中删除动态字符**,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30552037/