現在我創建一個雙指標來存盤從.txt檔案中獲取的一些單詞(因為string在 C 語言中沒有。)。我嘗試使用fgetsand fscanf。當我第一次運行fgets時fscanf,我可以將指標存盤在雙指標中。但是當我第二次運行它時,我發現第一次的值被完全覆寫了。這是代碼的一部分。
char **out = (char **)malloc(3 * sizeof(char *));
FILE *dictionary = NULL;
dictionary = fopen(filename, "r");
char store[6];
fscanf(dictionary, "%s", store);
printf("%s\n", store);
store[5] = '\n';
out[0] = store;
strcpy(store, "");
fscanf(dictionary, "%s", store);
out[1] = store;
printf("%s\n", out[0]);
printf("%s\n", out[1]);
fclose(dictionary);
return out;
txt檔案的內容是
cigar
rebut
sissy
上面代碼的預期結果是
cigar
cigar
rebut
但上面代碼的確切輸出是
cigar
rebut
rebut
我只是試圖一一存盤它們的值,但它似乎也篡改了我以前的值。我已經用陣列替換了指標,但這一直出現。我需要注意什么?還是有更好的選擇?
uj5u.com熱心網友回復:
在這里,您需要為每個一維字符陣列重新分配記憶體out[0] = (char*)malloc(5 * sizeof(char));并使用strcpy,因此以下是更正后的代碼。
char **out = (char **)malloc(3 * sizeof(char *));
FILE *dictionary = NULL;
dictionary = fopen(filename, "r");
char store[6];
out[0] = (char*)malloc(5 * sizeof(char));
fscanf(dictionary, "%s", store);
printf("%s\n", store);
strcpy(out[0], store);
out[1] = (char*)malloc(5 * sizeof(char));
fscanf(dictionary, "%s", store);
strcpy(out[1], store);
printf("%s\n", out[0]);
printf("%s\n", out[1]);
fclose(dictionary);
return 0;
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/425192.html
上一篇:當物件是指標時多載==和!==
下一篇:Phaser3多指標事件合二為一
