【发布时间】:2021-11-28 22:41:51
【问题描述】:
我想创建一个简单的 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);
}
【问题讨论】:
-
你事先知道数组的元素/字符串的数量吗?是10吗?或者 10 应该是数组中每个元素的大小。你需要澄清这一点。
-
是的,作为对帖子的澄清添加了这一点!