c - 当放入c中的数组时,字符串会变形

标签 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.

最佳答案

几个明显的问题:

strings[count]= tmp;

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

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

关于c - 当放入c中的数组时,字符串会变形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15712924/

相关文章:

c - C 中三元运算符的逻辑与

c - 嵌入式 C AVR 位填充数组

javascript - 如何在 JavaScript 对象上执行 `push` ?

string - 批量检查空用户输入

c - 如何调用 char * arr[]

iphone - NSString 为空

c - 预览窗口后屏幕状态的 Aero 功能是什么?

c - 为什么不能根据它指向的变量类型推断指针类型?

java - 需要数组,但即使我没有返回数组,也能找到整数

c# - 通过结构指针将结构数组从 C# 传递到 C