2
基本上,我希望我的代码的这一部分从输入的第一行读取句子的数量,然后是句子本身,并将它们存储在数组中(即使输入可以包含空格,最终阵列输入可能不是,不是首都)。 对于下面的输入如何动态创建一个字符串数组,并同时从数组条目中删除空格?
3
one two three
four five six (program didn't let me input another line, but just two more for the sake of the example.)
stack over flow
我想下面的输出
onetwothree
fourfivesix
stackoverflow
的资本化还没有实现,但我想这不会很难。 我的代码:
void main(){
int length1, length2,i,n;
scanf("%d", &length1);
char *sentenceArray1[length1];
char tempString[100000];
/*The array for storing the first set of sentences, and a temporary string used
for allocating memory in the next loop*/
for(i=0;i<=length1;i++){
fgets(tempString, 100000, stdin);
sentenceArray1[i]=malloc((strlen(tempString))*sizeof(char));
sentenceArray1[i]=tempString;
for(n=0;n<(strlen(tempString));n++){
if(tempString[n]==' '){
sentenceArray1[i][n]=tempString[n+1];
n++;
}
printf("%s",sentenceArray1[i]);
}
}
我的实际产量如下:
one two three
one two three
one two three
onettwo three
onettwo three
onettwo three
onettwotthree
onettwotthree
onettwotthree
onettwotthree
onettwotthree
onettwotthree
我很抱歉,如果标记偏了,这是我第一次发布提问。
你用malloc在一行上分配内存,然后在下一行失去对它的引用:'sentenceArray1 [i] = tempString;'。你最终得到所有指向tempString的sentenceArray [i]。你可能想要'strcpy()'或'strncpy()'tempString。 –