在C++中删除动态char**

b4k*_*ncs 0 c++ arrays dynamic char

披露:我正试图用严格的时间和内存限制来解决挑战.我通常会使用向量和字符串,但在这里我需要最快和最小的解决方案(实际上在时间限制之上运行的向量),所以我转向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;
}
Run Code Online (Sandbox Code Playgroud)

一切都运行得很好,没有删除数组(数组),但这是不可接受的,所以我该怎么做呢?我尝试了很多似乎合乎逻辑的变体,但我遇到了运行时错误.

vso*_*tco 7

它类似于分配,但是以相反的顺序,而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
Run Code Online (Sandbox Code Playgroud)

我假设这LENGTH是指针数组的长度char*.所以看起来你只进行了第一轮的解除分配

for (int i = 0; i < n; i++){
        delete substr[i]; // need delete[] substr[i] here
Run Code Online (Sandbox Code Playgroud)

delete代替delete[],你需要delete[] substr[i],而不是作为我的猜测是,substr[i]是一个char*指向数组的第一个元素的指针char被分配的S new[].你终于需要额外的了

delete[] substr;
Run Code Online (Sandbox Code Playgroud)