【发布时间】:2016-01-21 08:23:14
【问题描述】:
我有一个字符串数组,我正在尝试为其中一个字符串分配更多空间,以便更改字符串的值。
int catenate_strings (char** arr, int index1, int index2) {
char *new_string;
new_string = malloc(1000*sizeof(char));
if (new_string == NULL) {
printf("\nError allocating memory\n");
}
strcpy(new_string, arr[index1]);
strcat(new_string, arr[index2]);
arr[index1] = new_string;
}
但是,当我运行我的代码时,它会在某些情况下工作,但在其他情况下,它会在 index1 处复制字符串并将其放在 index1 + 1 处。
【问题讨论】:
-
您是否要“调整”字符串的大小?
-
请发MCVE。
-
当您执行
arr[index1] = new_string时内存泄漏,您正在丢失之前的字符串。 -
我正在尝试调整为字符串分配的空间,以便可以在其中放置更长的字符串。
-
另一种可能是
new_string的缓冲区溢出
标签: c arrays string malloc strcpy