我想创建一个简单的C程序,在循环中,当用户输入一个字符串时,该字符串会自动添加到一个数组中。我不知道如何在运行时做到这一点。任何帮助都将不胜感激。
编辑:为了清楚起见,这里10是数组的最大大小。我在考虑用一个数字初始化数组,然后当它达到最大大小(在本例中是10 )时扩展该大小(可能是乘数)。
Edit2:更具体地说,我希望它是这样的:第一次迭代向数组添加一个字符串,然后第二次迭代向数组添加另一个输入的字符串,依此类推。
现在,我的代码看起来像这样:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char* strings[10];
char *input_str;
printf("enter a string: ")
strings = malloc(sizeof(char)*10); //not sure if this is required but included anyway
//run a loop here to keep adding the input string
fgets((char)input_str, 1024, stdin);
}
发布于 2021-10-09 00:39:09
char* strings[10];
请注意,strings
是一个指向char
的十个指针的不可调整大小的数组,因此当您事先不知道元素的数量时,它对于动态分配不是很有用。
我将使用char **
上的realloc
和模运算符来检测何时执行realloc
,如下所示:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MULTIPLE 10
int main(void)
{
char **strings = NULL;
char str[1024];
size_t size = 0;
while (fgets(str, sizeof str, stdin))
{
if ((size % MULTIPLE) == 0)
{
char **temp = realloc(strings, sizeof *strings * (size + MULTIPLE));
if (temp == NULL)
{
perror("realloc");
exit(EXIT_FAILURE);
}
strings = temp;
}
strings[size] = malloc(strlen(str) + 1);
if (strings[size] == NULL)
{
perror("malloc");
exit(EXIT_FAILURE);
}
strcpy(strings[size], str);
size++;
}
for (size_t i = 0; i < size; i++)
{
printf("%s", strings[i]);
free(strings[i]);
}
free(strings);
return 0;
}
https://stackoverflow.com/questions/69504883
复制相似问题