C++删除c-strings数组/其他类型的数组

mic*_*ett 4 c++ memory-management cstring new-operator

[编辑]

好的,这是有道理的,谢谢sharptooth和CashCow.您不能删除分配为const的数据,这会使字符串文字无法解决.所以,如果我将初始化更改为如下所示:

char **groups = new char*[2];

char *s1 = new char[10];
char *s2 = new char[10];
char c1 = 'a';
char c2 = 'b';
for(int i = 0; i < 9; i++)
{
    s1[i] = c1;
    s2[i] = c2;
}
s1[9] = NULL;
s2[9] = NULL;

groups[0] = s1;
groups[1] = s2;
Run Code Online (Sandbox Code Playgroud)

硬代码我的for循环使它只迭代i = 1和i = 2,然后一切正常.

我注意到,int arraySize = sizeof arr / sizeof *arr;当数组分配new []而不是local时,似乎只能工作.这是因为我的原始char ** groups;变量衰减到指针,对吧?

现在我想知道,无论如何判断数据是否为常量?


[原版的]

我知道数组和指针是邪恶的,并且有一些称为向量和链表的伟大事物.

但是,在内存管理方面,我是一个新手,我感觉有点自虐.假设我创建一个C字符串数组.我知道,从这个问题和常见问题-精简版,你必须匹配type a = new type[len];delete[] a;.或者我认为.

FAQ-Lite讨论了如何在这里管理锯齿状数组,但他专注于矩阵,我不确定它是否适用于我正在做的事情.

这段代码对我来说很有意义,但是在一个断言(在Visual Studio 2008上调试)上失败了delete[] a;.这有什么问题,我该如何完成这项任务?

#include <iostream>
using namespace std;

int main(int argc, char* argv[])
{
    // Initialize array of C-strings
    char *groups[] = {"testing1", "testing2"};

    // Sanity check
    cout << groups[0] << endl;
    cout << groups[1] << endl;

    // Compute size
    int arrsize = sizeof groups / sizeof groups[0];
    cout << arrsize << endl;

    for (int i = 0; i < arrsize; i++)
    {
        // Since each string is a char array, free string memory with delete[]
        cout << "Deleting element #" << i << endl;
        delete[] groups[i];
    }
    cout << "Freeing pointer array." << endl;

    // Free the memory storing the pointers
    delete[] groups;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

sha*_*oth 9

您尝试释放字符串文字 - 这是未定义的行为:

char *groups[] = {"testing1", "testing2"};
delete[] groups[i];
Run Code Online (Sandbox Code Playgroud)

只调用delete[]返回的指针new[].