![](/img/trans.png)
[英]How to dynamically allocate memory in an array of strings for some new string and copy that string into the dynamically allocated space in C?
[英]How to add a dynamically allocated string to array of strings in C?
我必须编写一个将给定字符串添加到字符串数组的函数。
char **add_string(char **array, const char *string)
{
array = realloc(array, (sizeof(string)) * sizeof(char *));
int i = 0;
while (array[i] != NULL){
i++;
}
array[i] = malloc((strlen(string) + 1));
strcpy(array[i], string);
array[i + 1] = NULL;
return array;
}
根据Valgrid的说法,此刻我出现内存泄漏。 我没有正确使用malloc,但是我不知道如何解决它。 我将衷心感谢您的帮助。
realloc在给定第二个参数的情况下分配了一个新的大小,但您并未增加该大小,因此,基本上,每次调用函数时,它都会分配相同的大小而不增加分配的面积。
您需要将数组中的当前字符串数传递给add_string,然后在add_string中递增它
char** add_string(char** array, int* size, const char* string)
{
char* newArray = realloc(array, (*size + 1) *sizeof(char*) );
newArray[*size] = malloc(strlen(string)+1);
strcpy(newArray[*size], string);
*size += 1;
...
}
您还应该通过检查返回值来检查重新分配是否成功。
通常,上述方法不是处理大小增加的非常有效的方法,因为您每次都在调用realloc,这非常耗时。 相反,您应该分块分配,然后跟踪已用完多少块,当块用完时重新分配一个新块。
您对array
重新分配已中断,它需要进行搜索以找出数组有多长时间,并假设它始终是“紧密”分配的(最后分配的元素是唯一一个为NULL
元素)。
char **add_string(char **array, const char *string){
int i = 0;
while (array[i] != NULL){
i++;//First, count the elements and find NULL element
}
array[i] = malloc(strlen(string) + 1);//or strdup(string);
strcpy(array[i], string);
char **temp;
temp = realloc(array, (i+1+1) * sizeof(char *));
if(temp == NULL){
perror("realloc at add_string");
} else {
array = temp;
array[i + 1] = NULL;
}
return array;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.