将数据从文件放入C中的数组

这是我的代码。

#include  #include  int main() { //Vars FILE *fp; char word[9999], *arrayOfWords[9999]; int wordCount = 0, i; //Actions fp = fopen("data.txt", "r"); if(fp != NULL) { while(!feof(fp)) { fscanf(fp, "%s", word); arrayOfWords[wordCount] = word; wordCount++; } for(i = 0; i < wordCount; i++) { printf("%s \n", arrayOfWords[i]); } puts(""); } else { puts("Cannot read the file!"); } return 0; } 

我试图从文本文件中读取一些数据并将其存储到数组中。 我在循环中时一切都很好,但是当我离开那里时,我的数组中任何索引的任何值都填充了文件的最后一个单词。 任何人都可以帮我找出我正在做的错误吗?

数据文件:

 Hello there, this is a new file. 

结果:

 file. file. file. file. file. file. file. file. 

任何帮助,将不胜感激!

您的代码中至少有两个值得关注的问题。 char word[9999], *arrayOfWords[9999];arrayOfWords定义为9999个char pointers的数组。 这是一个值得关注的问题。

另一点是arrayOfWords[wordCount] = word; 。 这里存储新读取的单词,需要分配空间,因为arrayOfWords是一个指针数组。 请找到您修改后的代码,如下所示。

 int main() { //Vars FILE *fp; char arrayOfWords[30]; int wordCount = 0, i; //Actions fp = fopen("data.txt", "r"); if(fp != NULL) { while(!feof(fp)) { fscanf(fp, "%s", &arrayOfWords[wordCount]); wordCount++; } puts(""); for(i = 0; i < (wordCount - 1); i++) { puts(arrayOfWords[i]); } puts(""); } else { puts("Cannot read the file!"); } return 0; } 

您需要为数组的每个单独成员分配内存(使用malloc或通过给出数组的第二个维度并声明它的类型为char而不是char* )。 你做的是类似于:

 char *s; scanf("%s", s); 

这在C不起作用。 实际上你在这里有UB(未定义的行为),因为指针没有被初始化。

编辑:你得到数组中的所有字段,指向你的数组word ,一旦你读了字,你应该为字符串分配新的内存,然后strcpy word

这个:

 arrayOfWords[wordCount] = word; 

不会将当前单词复制到单独的存储中,它只是指定另一个指针指向与word相同的存储空间。 所以你最终得到了一个指向同一个word组的指针数组。 您需要为每个单词单独分配内存并复制构成每个单词的字符(和NULL终止符),而不是指针。