【问题标题】:Using strtok() on Linked List在链表上使用 strtok()
【发布时间】:2014-01-02 08:53:04
【问题描述】:

我是 c 新手,我正在尝试构建一个双向链表。 我有一个小问题,希望得到您的帮助。 我需要输入一个如下所示的字符串:

(word)_#_(year)_#_(english synonyms)_#_(hebrew synonyms)

事实上,我需要将每个单词存储在我的链表中,所以我使用 strtok() 来分隔 _#_ 符号。这里的问题是当我输入我的字符串来测试我是否可以将它分开但它给了我以下消息:

Program Using strtok()(39583,0x7fff7a83f310) malloc: * 错误 对象 0x7fff5fbff668: 被释放的指针未被分配

现在我想我找到了问题,尽管我无法解决它。 这是我的代码,我在问题所在的程序上发表了评论。很想得到你的帮助

 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>

 typedef struct dictionary {
 char word[100];
 int year[10];
 char eng_synonyms[100];
 char heb_synonyms[100]; } dictionary;

dictionary parse_dictionary(const char *s) {
 char *copy = strdup(s); // Make a copy for strtok
 char *tok = strtok(copy, "_#_");
 dictionary result = {0};

 if (tok != NULL)
 {
     result.word[99] = *strdup(tok);
 }
 else
 {
     result.word[99] = *strdup("");
 }

 tok = strtok(NULL, "_#_");

 if (tok != NULL)
 {
     result.year[9] = *strdup(tok);
 }
 else
 {
     result.year[9] = *strdup("");
 }

 tok = strtok(NULL, "_#_");
 if (tok != NULL)
 {
     result.eng_synonyms[99] = *strdup(tok);
 }
 else
 {
     result.eng_synonyms[99] = *strdup("");
 }
 free(copy); // Clean up temporaries
 return result; }

   int main(void) {
 char dictionarys[100];
 printf("Enter a string\n");
 scanf("%s", dictionarys);

 dictionary def = parse_dictionary(dictionarys);
 printf("%s\n%s\n%s\n%s\n", def.word, def.year, def.eng_synonyms, def.heb_synonyms); // format specifies char* but argument has type *int
 free(def.word);
 free(def.year);
 free(def.eng_synonyms);
 free(def.heb_synonyms);
 return 0; }

【问题讨论】:

  • 案例char word[100]strcpy(result.word, tok);,案例char *wordresult.word = strdup(tok);
  • format specifies char* but argument has type *int 因为yearint 的数组(不是字符串)
  • 和 strtok 不用于按字符串剪切标记。因为 strtok 中的分隔符不是字符串。它是字符(分隔符列表)。

标签: c string linked-list


【解决方案1】:

你不应该在静态对象上调用 free。例如。 def.word 是一个大小为 100 的静态数组,您不应该释放它,其他结构成员也是如此。只应为动态分配的对象调用 Free(例如使用 malloc)。

【讨论】:

    【解决方案2】:

    代码行result.word[99] = *strdup(tok); 将静态数组result.word 的第99 个字符设置为tok 的第一个字符(* 仅取消引用第一个字符)。您应该使用strcpymemcpy(memcpy reference) 而不是将tok 的值复制到result.word

    另外,在使用结构之前,最好使用 memset (memset reference) 之类的函数对结构进行零填充

    dictionary result;
    memset(&result,0,sizeof(dictionary));
    

    对于dictionaryint year[10] 成员,它是一个数组是没有意义的。它应该是一个普通的int。您需要将其读取为char*,然后使用函数atoi (atoi reference) 将其转换为int

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-21
      • 2013-09-26
      相关资源
      最近更新 更多