【发布时间】:2013-04-01 19:30:50
【问题描述】:
我有下面的代码,其中包含一个动态的字符串数组。我在解除分配生成的每个单独字符串时遇到问题。我以为我可以只包含一个新的 for 循环来释放它们,但这不起作用。我该怎么做?
//A dynamically allocated array of char pointers
int numOfStrings = 10, numOfChars = 32;
char** data = new char*[numOfStrings];
//Generate each each individual string
for(int i = 0; i <numOfStrings; i++)
data[i] = new char[numOfChars];
//moves the elements 1-5 in the array to the right by one
int index = 1, boundary = 5, sizeToMove = (boundary - index) * sizeof(numOfChars);
memmove(&data[index + 1],&data[index],sizeToMove);
for(int i=0;i < numOfStrings; i++)
delete [] data[i]; //this line is causing an exception on its first call (I've also tried delete data[i].
delete[] data;
【问题讨论】:
-
使用C++的工具会容易很多。
std::vector<std::string> data(numOfStrings); -
您正在移动数组本身的内存,您不想获取数据的地址,而是获取数据指向的指针。还要检查你的 sizeof(numOfChars) 因为它相当于 sizeof(int) 你确定你想要那个吗?