好吧,這樣說起來很有道理,謝謝你和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