【问题标题】:Using strings from a text file is working different than using literal strings?使用文本文件中的字符串与使用文字字符串的工作方式不同?
【发布时间】:2014-05-20 01:13:11
【问题描述】:

我有一个 C 程序,它从文本文件中读取字符串并使用这些来创建放置在哈希表 (d_table) 中的结构。它在循环中逐行读取文件。我得到的运行时问题是,使用从文件中获取的字符串添加的每个条目似乎仍然指向最近读取的内容(所以 char word[] 只​​是“。”),但如果它是硬编码一些条目(如第二个 ht_insert)然后它完全按预期工作。这让我觉得我在 C 如何处理字符串方面遗漏了一些明显的东西......

文本文件的一行看起来像:“Test This is a test line”,最后一行是“.”

入口结构:

struct d_entry {
  char *word;
  char *desc;
};

我认为问题不是在程序中的 create_entry 或其他地方引起的,否则为什么硬编码的条目可以正常工作?据我所知,超出这一点,无论字符串是硬编码的还是从文件中获取的,条目都应该是无法区分的:

struct d_entry * create_entry(char *word, char*desc) {
  struct d_entry * e;
  e = (struct d_entry *) malloc(sizeof(struct d_entry));
  e->word = word;
  e->desc = desc;
  return e;
}

这是从文件读取函数中获取的必要代码。我已经测试了很多,文件处理和从文件中提取字符串似乎工作正常:第一个 ht_insert 调用导致运行时问题,第二个调用是硬编码条目的示例,它工作正常:

int read_from_file(const char * filename) {

  char word[40];
  char desc[200];

  FILE * fp;
  fp = fopen(filename, "r");

  fscanf(fp, "%s %[^\n]]", word, desc);

  while (word[0] != '.') {
    ht_insert (d_table, create_entry(word, desc)):
    ht_insert (d_table, create_entry("test", "test desc"));
    fscanf(fp, "%s %[^\n]", word, desc);
  }

fclose(fp);
return 1;
}

任何帮助将不胜感激,谢谢。

【问题讨论】:

  • read_from_file 看起来像是被剪掉了
  • 还有一些其他的代码我没有在这里包含,因为它有不同的用途并且工作正常。添加了 fclose 并返回。

标签: c string pointers scanf


【解决方案1】:
create_entry(strdup(word), strdup(desc))

【讨论】:

    【解决方案2】:

    使用strdup 为您存储在数据结构中的每个字符串制作一个堆副本。

    对从文件(到临时缓冲区)读取的字符串和静态字符串都执行此操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-09
      • 2021-11-18
      • 2015-07-31
      • 2021-09-27
      • 2020-01-03
      • 2016-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多