好吧,这样说起来很有道理,谢谢你和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循环,这样就只能通过我迭代= 1和I = 2,则一切正常。
我注意到int arraySize = sizeof arr/sizeof *arr;
似乎只有当数组分配新[]而不是本地。这是因为我的原始char ** groups;
变量衰减为一个指针,对吧?
现在我想知道,有无论如何告诉数据是否是常量?
[原文]
我知道arrays and pointers are evil,并有这些伟大的事情称为向量和链表。
但是,当谈到内存管理时,我是一个新手,我感觉有点受虐狂。假设我制作了一系列C字符串。我知道从this question和FAQ-Lite,你必须匹配type a = new type[len];
与delete[] a;
。或者我想。
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;
}
你有没有注意到你在不调用`new()`前删除[]`? – Simone 2010-11-29 09:43:24
不是数组和指针是邪恶的,它们的滥用是邪恶的。 – sharptooth 2010-11-29 09:44:43
他们是邪恶的,他们已经造成了很多麻烦,因为在任何情况下都很难让他们正确,并且有其他选择。不是因为他们不应该被允许使用。 – stefaanv 2010-11-29 10:28:51