【发布时间】:2020-09-02 00:26:23
【问题描述】:
由于某种原因,当我将单词从文件复制到数组时,最后一个元素正在替换先前索引中的所有内容;但是,我通过将文本添加到索引 0 和 1 来测试数组工作正常,然后通过“文件循环”。请看一下:
FILE *file = fopen("words.txt", "r");
if (file == NULL){
printf("...\n");
return false;
}
char *words[172805];
//Array test
words[0] = "abc";
words[1] = "bcde";
printf("%s, %s\n", words[0], words[1]);
// Copy words in text document to 'words' array.
while (!feof(file)) {
if (fgets(arraywordindic, 15, file) != NULL) {
//Remove \n from word in arraywordindic
arraywordindic[strcspn(arraywordindic, "\n")] = '\0';
words[i] = arraywordindic;
printf("%s\n", words[i]);
i++;
if (i == 4) {break;}
}
}
for (i = 0; i < 4; i++) {
printf("%s, ", words[i]);
}
fclose(file);
上面代码的输出是:
abc bcde
一个
AA
啊哈
AAHED
啊啊啊啊啊啊啊啊啊啊啊啊啊啊
你知道为什么会这样吗?谢谢。
【问题讨论】:
-
为什么是
172805?这是一个非常具体的数字。 -
我需要存储在数组中的单词数是172806。
-
那是你不想在 C 中做出的那种假设。如果是这样的话,你也是一个空头。最好使用
realloc或链表结构根据需要动态分配越来越多的内存。 -
谢谢。不是为了这个练习,这就是我们需要的所有单词量。对于动态数组,我使用内存分配函数,而不是你提到的。
-
哦,我知道了,谢谢。