2017-11-14 10 views
-1

異なる文字列をchar *の配列に保存しようとしていますが、何らかの理由で同じ文字列を配列のすべての要素に保存しています。要素。同じ文字列が配列のすべての要素に格納されます

char string[99]; 
char line[99]; 
FILE* out = fopen("data.out", "w"); 
char *words[999]; 
int wcount = 0; 


while(fscanf(fpointer, "%s", string) != EOF) 
{ 
    if((strlen(string) + strlen(line))-1 <= number) 
    { 
     strcat(line, string); 
     char word[99]; 
     strcpy(word, string); 
     words[wcount] = word; 
     printf("should have saved %s at %d\n", word, wcount); 
     wcount++; 

     if(strlen(line) < number) 
     { 
      strcat(line, " "); 
     } 
     puts(line); 
    } 
    else 
    { 
     fprintf(out,"%s", line); 
     fprintf(out, "\n"); 
     strcpy(line, string); 
     strcat(line, " "); 
    } 
} 

fprintf(out, "%s", line); 

printf("wcount is %d\n", wcount); 
puts(words[0]); 
puts(words[1]); 
puts(words[2]); 

「保存されているはずです」で始まるprint文は単語の配列に保存されますが、最後のprint文が保存された最後の言葉は、配列の各要素であることを示してしなければならない正しい文字列を出力します。

+5

この文では、単語[wcount] = word;配列ワードのすべての要素は、ローカル変数ワード(の最初の文字)の同じアドレスを含みます。だから、コードは意味をなさないし、さらには未定義の振る舞いを持っています。 –

+0

あなたはどのバージョンのCをコンパイルしていますか? –

+0

すべてのポインタが同じ 'word'を指しているので、* not *は異なります。 (そして、最後にそれを印刷しようとすると、 'word'はもう存在しません)。あなたは、それにポインタを設定するだけでなく、いくつかのストレージに単語をコピーする必要があります。 –

答えて

1

多分このようなものが欲しいですか? 今すぐテストできません。

char **words = NULL; 
while(fscanf(fpointer, "%s", string) != EOF) 
{ 
    if((strlen(string) + strlen(line))-1 <= number) 
    { 
     strcat(line, string); 
     words = realloc(words,sizeof(char *)*(wcount+1)); 
     words[wcount] = malloc(sizeof(char)*(strlen(string)+1)); 
     strcpy(words[wcount], string); 
     printf("should have saved %s at %d\n", words[wcount], wcount); 
     wcount++; 

     if(strlen(line) < number) 
     { 
      strcat(line, " "); 
     } 
     puts(line); 
    } 
    else 
    { 
     fprintf(out,"%s", line); 
     fprintf(out, "\n"); 
     strcpy(line, string); 
     strcat(line, " "); 
    } 
} 

fprintf(out, "%s", line); 

printf("wcount is %d\n", wcount); 
puts(words[0]); 
puts(words[1]); 
puts(words[2]); 
+0

これはうまくいきません。 "-bash:./wordproc.c:Permission denied"と書かれていますが、もともとchar * words = NULLではなくchar * words [999] – McLovinIt

+0

cファイルは実行可能ではありません./a.outを実行することを意味しましたか?(あなたがコンパイルしたと仮定して)?あなたはおそらく、配列を動的に割り当てるために私のソリューションを使いたいと思っています。無限の言葉を保存することができます。 – TheAschr

+0

ありがとうございました – McLovinIt

関連する問題