【问题标题】:C - Array is not working when copying files from text fileC - 从文本文件复制文件时数组不起作用
【发布时间】: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 或链表结构根据需要动态分配越来越多的内存。
  • 谢谢。不是为了这个练习,这就是我们需要的所有单词量。对于动态数组,我使用内存分配函数,而不是你提到的。
  • 哦,我知道了,谢谢。

标签: arrays c file


【解决方案1】:

看起来您一遍又一遍地设置指向完全相同的缓冲区的指针。您需要复制字符串,或者换句话说:

words[i] = strdup(arraywordindic);

在 C 中,当你说 char* x = y 时,它复制该字符串的内容,它复制 指向该字符串的指针

【讨论】:

    猜你喜欢
    • 2015-11-05
    • 1970-01-01
    • 2016-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多