2013-03-29 31 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

相关问题