4

[编辑]

好的,这是有道理的,谢谢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;变量衰减为指针,对吗?

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


[原来的]

我知道数组和指针是邪恶的,并且有这些很棒的东西叫做向量和链表。

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

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

这段代码对我来说很有意义,但在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;
}
4

2 回答 2

9

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

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

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

于 2010-11-29T09:43:02.690 回答
1

文字字符串是类似“testing1”的表达式。它们是 const char * 类型。它们不能被修改,也不能被删除。实际文本通常位于程序的静态只读内存区域中。

您可以像这样构造一个可写的 char 数组:

char group[] = "testing1";

这是可修改的,但您不能删除它,也不能扩展它以使其更大。它还具有本地范围,因此您不能从函数中返回它。

于 2010-11-29T09:54:57.293 回答