我從檔案中讀到單詞。當我將它們放入結構中時,它會寫入相同的值。什么是問題,我該如何解決
- IDE:VsCode
- 編譯器:mingw64-gcc-g
檔案內容;
{Sam}
{Patrick}
{Philips}
我的代碼;
struct Sentence
{
char *word;
};
struct Sentence *words[20];
void readFile(const char *path, char *fileName)
{
int wordpointer = 0;
int len = strlen(fileName);
FILE *fp;
if ((fp = fopen((path), "r")) != NULL)
{
char ch = fgetc(fp);
while (ch != EOF)
{
if (ch == '{')
{
int counter = 0;
while (ch != EOF)
{
char word[20];
ch = fgetc(fp);
if (ch == '}')
{
//printf("%s\n",word);
struct Sentence *st = malloc(sizeof(struct Sentence));
st->word = word;
words[wordpointer] = st;
wordpointer ;
break;
}
word[counter ] = ch;
}
}
ch = fgetc(fp);
}
fclose(fp);
}
for (int i = 0; i < wordpointer; i )
printf("%s\n", words[i]->word);
}
我可以在注釋行的 printf 函式中得到正確的輸出,但是當我列印 Struct 時,如下所有的值都是檔案中的最后一個單詞。
輸出;
Philips
Philips
Philips
uj5u.com熱心網友回復:
在這個while回圈中
while (ch != EOF)
{
char word[20];
//...
所有指標 st->word = word; 指向同一個區域變數字
if (ch == '}')
{
//printf("%s\n",word);
struct Sentence *st = malloc(sizeof(struct Sentence));
st->word = word;
words[wordpointer] = st;
wordpointer ;
break;
}
宣告為
st->word = word;
所以退出函式后指標將無效。
您需要為每個字串分配記憶體并復制輸入的字串。此外,您需要在它們后面加上終止零字符'\0'。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/514900.html
