字符串在c中放入数组时会变形

时间:2013-03-29 23:18:26

标签: c arrays string

我试图从txt文件中取出每个单词,然后将其放入数组中。我的代码从文件中获取每个单词并将其保存为字符串没有问题。然而,当我尝试将字符串放入一个数组并将其打印出来时,只打印出最后几行并且它们都被扭曲了。

这是我的代码:

  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.

1 个答案:

答案 0 :(得分:1)

一些明显的问题:

strings[count]= tmp;

这只是一个指针赋值。每次进行分配时,tmp都具有相同的值。每次循环时都需要分配一个新字符串。并使用strcpy复制它。

其次,你的print循环假设字符串数组是用空指针初始化的。它不是。你根本没有初始化它。