释放C结构体内部的char数组 [英] Free a char array that is inside a struct in C
问题描述
我有一个结构,其中包含一个字符串数组(char数组)和一个int以表示该数组的最大容量。
I have a struct that contains an array of strings (char arrays) and an int for the maximum capacity of the array.
typedef struct ArrayList
{
char **array;
int capacity;
}
使用malloc在自己的方法中初始化数组。
The array is initialized with malloc in its own method.
list->array = malloc(sizeof(char *) * templength);
然后将各个字符串初始化为
And the individual strings are initialized as
list->array[nextEmptyString] = malloc(sizeof(str));
strcpy(list->array[nextEmptyString], str);
我需要能够从内存中清除与该数组有关的所有内容,然后传递一个指向该数组的新指针数组,但是当我尝试在释放数组之前释放单个字符串时,它会扰乱新数组。
I need to be able to clear everything about that array from memory and then pass a new pointer to that array, however when I attempt to free the individual strings before freeing the array it scrambles the new array.
for (word = 0; word < list->capacity; word++)
free(list->array[word]);
free(list->array);
list->array = newArray;
其中list是ArrayList,而newArray是字符串数组。如果我注释掉for循环,则代码可以正确运行,但是难道我不只是一堆孤立的字符串在内存中浮动吗?
Where list is an ArrayList and newArray is an array of strings. The code runs correctly if I comment out the for loop, but then don't i just have a bunch of orphaned strings floating around in memory?
预期的输出是什么例如将Pierre添加到L1 ...
,而我却得到将éc添加到L1 ...
The intended output is something like Adding Pierre to L1 ...
and instead I get Adding �c� to L1 ...
推荐答案
在数组中分配字符串时,
When allocating the strings in the array,
malloc(sizeof(str))
仅为<$ c $分配足够的空间c> char * ,而不是它指向的字符串(除非 str
是普通数组而不是指针)。相反,请尝试
only allocates enough space for a char *
, rather than the the string it points to (unless str
was an ordinary array rather than a pointer). Instead, try
malloc(strlen(str) + 1)
为字符串中的字符分配足够的空间以及一个终止的null。
to allocate enough room for the characters in the string plus a terminating null.
这篇关于释放C结构体内部的char数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!