C++删除c字符串数组/其他类型的数组

标签 c++ memory-management new-operator cstring

[编辑]

好的,这是有道理的,谢谢 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;

对我的 for 循环进行硬编码,使其只遍历 i=1 和 i=2,然后一切正常。

我注意到 int arraySize = sizeof arr/sizeof *arr; 似乎只有在使用 new[] 而不是本地分配数组时才有效。这是因为我原来的 char ** groups; 变量衰减为指针,对吗?

现在我想知道,有没有办法判断数据是否为常量?


[原创]

我知道arrays and pointers are evil ,还有称为 vector 和链表的伟大事物。

但是,我是内存管理方面的新手,感觉有点自虐。假设我制作了一个 C 字符串数组。我从this question知道以及您必须将 type a = new type[len];delete[] a; 匹配的 FAQ-Lite。或者我认为。

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

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

#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;
}

最佳答案

您尝试解除分配字符串文字 - 这是未定义的行为:

char *groups[] = {"testing1", "testing2"};
delete[] groups[i];

仅对 new[] 返回的指针调用 delete[]

关于C++删除c字符串数组/其他类型的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4302467/

相关文章:

ios - 如果我现在开始学习iOS开发,我应该使用垃圾回收功能吗?

r - 如何列绑定(bind)两个ffdf

c++ - 为什么我们应该重载/覆盖新的和删除?

c++ - C++ : 中用于 GUI 的 WXwidgets

c++ - 使用 C++/boost 套接字的简单客户端/服务器在 Windows 下工作,但在 Linux 下失败

java - 实例变量如何在 Google App Engine 上工作? [Java]

c++ - 在链表前面添加新节点的问题

c++ - 系统 ("pause") 不适用于 freopen

c++ - WinAPI如何在未实现WinMain时确保编译失败

Java 我想我的问题是如何重用一个对象来将 2 条记录添加到我的数据库程序中