C 字符串数组插入问题

C 字符串数组插入问题,c,arrays,string,C,Arrays,String,我想创建一个字符串数组,用户在其中输入数据并将其存储在数组中..我不知道该怎么做-(我读了几本C语言书) 任何帮助都将不胜感激 到目前为止,我尝试的是: int choice; printf("enter the number of the strings: "); scanf("%d",&choice); char **str=(char **)malloc(100); int i; for(i=0;i<choice;i++) {

我想创建一个字符串数组,用户在其中输入数据并将其存储在数组中..我不知道该怎么做-(我读了几本C语言书) 任何帮助都将不胜感激 到目前为止,我尝试的是:

int choice;
    printf("enter the number of the strings: ");
    scanf("%d",&choice);
char **str=(char **)malloc(100);
    int i;



    for(i=0;i<choice;i++)
    {
        printf("enter %dth element ",i+1);
            str[i]=(char *)malloc(10);
        scanf("%s",str[i]);
    }
    printf("%s",str[0]);
int选择;
printf(“输入字符串的数目:”);
scanf(“%d”,选择(&C);
char**str=(char**)malloc(100);
int i;

对于(i=0;i您没有为字符串分配任何空格。如果您对有界数组没有问题,您可以将str定义为
char str[100][128]
每个字符串最多有100个字符。至少在您学习一些基本的动态分配之前。

如果我读对了,您已经定义了一个指向100个字符数组的指针。您真正想要的是长度为100个字符的“选择”数组,我想
char str[choice][100]

然后,您可以像读取和打印字符串输入一样使用数组。

在读取字符串之前,您必须为每个字符串分配并初始化空间。如果您知道输入字符串的长度,那么malloc/calloc还有那么多空间可以猜测大小,但这将浪费空间。
You will have to allocate and initialize space for each string before reading them in. If you know he length of your input string then malloc/calloc that much space else guess a size but that would be wastage of space.

for(i=0;i<choice;i++)
     {
         printf("enter %dth element ",i+1);
         str[i] = malloc(sizeof(char)*length);
         memset(str[i],0,length);
         scanf("%s",str[i]);
     }  

对于(i=0;i你只需要阅读更多我想,这是非常基本的,基本的技能可以让你做到。是的,应该!但问题是程序正在终止!我应该希望它终止!我不想运行一个我希望终止的程序,它会永远持续下去。我知道动态分配-我可以做到。是的,动态分配是解决问题的方法go.但通常当您这样输入时,您不知道字符串的大小,因此会使用、复制和刷新一些大的缓冲区。str[i]=malloc(sizeof(char)*length);此行不起作用!您必须指定“length”…但Jonathan建议的是方法。