[编辑]
好的,这是有道理的,谢谢 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/