我想创建一个字符串数组,用户将在其中输入数据并将数据存储在数组中。我不知道如何做到这一点 - (我读过几本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]);
答案 0 :(得分:1)
您没有为字符串分配任何空格。如果你对有界数组没问题,可以将str定义为char str[100][128]
,每个字符串最多包含128个字符串。至少在你学习一些基本的动态分配之前。
答案 1 :(得分:1)
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]);
}
答案 2 :(得分:0)
如果我正确读取这个,你已经定义了一个指向100个字符数组的指针。你真正想要的是“选择”数组长度为100的字符我认为char str[choice][100]
然后你就可以使用你的数组来读取和打印字符串输入。