C语言 为什么realloc覆盖字符串?



我正在尝试编写一个动态增加char数组的程序。当我打印数组时,它会增加数组,但是旧的数据会被用户输入的内容覆盖,并且每次都会重复输入。有人能帮帮我吗?

所需输出:

Item1
Item2
Item3

当前输出:

Item3
Item3
Item3
下面是我的代码:
int main()
{
int length = 1;
char *list;
list = calloc(length, length * sizeof(char *));
char *temp;
char user_input[100];
while (1) {
fgets(user_input, 100, stdin);
user_input[strcspn(user_input, "n")] = 0;
temp = realloc(list, length * sizeof(char));
strcpy(temp, user_input);
list = temp;
printf("****LIST****nn");
for (int item = 0; item < length; item++) {
puts(list);
}
printf("n");
length++;
}
return 0;
}

list应该是char **,因为它是一个字符串数组,而不是单个字符串。

您需要为每个列表项分配一个单独的字符串,以保存该行的副本。

int main()
{
int length = 0;
char **list = NULL;
char user_input[100];
while(1)
{
fgets(user_input,sizeof user_input,stdin);
user_input[strcspn(user_input,"n")] = 0;
char *temp = malloc(strlen(user_input) + 1);
if (!temp) {
printf("Unable to allocate input stringn");
exit(1);
}
strcpy(temp,user_input);
length++;
char **temp_list = realloc(list, length * sizeof(*temp_list));
if (!temp_list) {
printf("Unable to realloc listn");
exit(1);
}
list = temp_list;
list[length-1] = temp;
printf("****LIST****nn");
for(int item = 0;item < length;item++)
{
printf("%sn", list[item]);
}
printf("n");
}
return 0;
}

最新更新