我想动态分配字符串数组,但我不确定该怎么做。所以我想到制作一个结构并动态分配该结构。所以我编写了下面的代码,但是这段代码会导致断言失败。
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char str1[20];
char str2[20];
} String;
int main(void)
{
String * list;
list = (String *)malloc(sizeof(String));
int i = 1;
for (; i < 6; i++) {
realloc(list, i * sizeof(String));
printf("Input String 1: ");
scanf("%s", list[i - 1].str1);
printf("Input String 2: ");
scanf("%s", list[i - 1].str2);
}
for (i = 0; i < 5; i++)
printf("%s\t%s\n", list[i].str1, list[i].str2);
free(list);
}
我做错了什么,我该如何解决这个问题?
谢谢:)
最佳答案
realloc
的手册页说:
The realloc() function returns a pointer to the newly allocated memory, which is suitably aligned for any kind of variable and may be different from ptr, or NULL if the request fails.
新的指针可能和你传递给realloc
的指针不同,所以你需要收集并使用realloc
返回的指针。
关于c - 动态分配字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44340188/