2013-03-29 34 views
-2

我試圖從txt文件中取出每個單詞,然後將其放入數組中。我的代碼沒有問題從文件中取出每個單詞並將其保存爲一個字符串。但是,當我嘗試將字符串放入一個數組並將其打印出來並僅打印出最後幾行時,它全部失真。將字符串放入數組c時出現扭曲

這裏是我的代碼:

typedef char * string; 
    string strings[100]; 
    FILE* file = fopen(argv[1], "r"); 
    char line[256]; 

    while(fgets(line, sizeof(line), file)) 
    { 
    string tmp = strtok(line, " ,'.-"); 

    while(tmp != NULL) 
    { 
     strings[count]= tmp; 
     tmp = strtok(NULL, " ,.'-;"); 
     count++; 
    } 
    } 

    int c2 = 0; 

    while(strings[c2] != NULL) 
    { 
    printf("%s, ", strings[c2]); 
    c2++; 
    } 

    return 0; 
} 

下面是從文件,我在閱讀的文本:

 
There is a place where the sidewalk ends 
And before the street begins, 
And there the grass grows soft and white, 
And there the sun burns crimson bright, 
And there the moon-bird rests from his flight 
To cool in the peppermint wind. 
+6

'typedef char * string' - **從不。永遠。** – 2013-03-29 23:20:35

+2

恭喜。您有一個緩衝區溢出漏洞。 – 2013-03-29 23:21:41

+2

所有指針指向'line',並被每個'fgets'覆蓋。 –

回答

1

幾個明顯的問題:

strings[count]= tmp; 

這是隻是一個指針分配。每次你做任務時,tmp都有相同的值。每次循環時都需要分配一個新字符串。並使用strcpy來複制它。

其次,您的打印循環假定字符串數組使用空指針進行初始化。不是這樣。你根本沒有初始化它。

+0

非常感謝你的幫助 – user2158720

相關問題