简体   繁体   English

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

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

For some reason when I copy words from a file to an array, the last element is replacing all the contents from the previous indexes;出于某种原因,当我将单词从文件复制到数组时,最后一个元素替换了先前索引中的所有内容; however, I tested that the array is working fine before going throught the 'file loop' by adding text to index 0 and 1. Please take a look:但是,我通过向索引 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);

The output of above code is:以上代码的output为:

abc bcde abc bcde

A一种

AA AA

AAH AAH

AAHED AAHED

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

Do you happen to know why this is happening?你碰巧知道为什么会这样吗? Thank you.谢谢你。

It looks like you're setting pointers to exactly the same buffer over and over.看起来您正在一遍又一遍地将指针设置为完全相同的缓冲区。 You need to copy the strings, or in other words:您需要复制字符串,换句话说:

words[i] = strdup(arraywordindic);

In C when you say char* x = y this does not copy the contents of that string, it copies the pointer to the string .在 C 中,当您说char* x = y时,这不会复制该字符串的内容,而是复制指向该字符串的指针。

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

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