簡體   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