繁体   English   中英

C - 从文本文件复制文件时阵列不工作

[英]C - Array is not working when copying files from text file

出于某种原因,当我将单词从文件复制到数组时,最后一个元素替换了先前索引中的所有内容; 但是,我通过向索引 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);

以上代码的output为:

abc bcde

一种

AA

AAH

AAHED

阿赫德,阿赫德,阿赫德,阿赫德,

你碰巧知道为什么会这样吗? 谢谢你。

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

words[i] = strdup(arraywordindic);

在 C 中,当您说char* x = y时,这不会复制该字符串的内容,而是复制指向该字符串的指针。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM