这是我的代码。
#include <stdlib.h>
#include <stdio.h>
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.
如有任何帮助,我们将不胜感激!
最佳答案
您需要为数组的每个单独成员分配内存(使用 malloc 或通过提供数组的第二个维度并将其声明为 char
类型而不是 char*
).你所做的类似于:
char *s;
scanf("%s", s);
这在 C
中是行不通的。实际上这里有 UB(未定义行为),因为指针未初始化。
编辑:你让数组中的所有字段指向你的数组 word
相反,一旦你读了 word 你应该为字符串分配新的内存然后 strcpy
word
放入其中。
关于c - 将文件中的数据放入C中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14940633/