【发布时间】: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 *word:result.word = strdup(tok); -
format specifies char* but argument has type *int因为year是int的数组(不是字符串) -
和 strtok 不用于按字符串剪切标记。因为 strtok 中的分隔符不是字符串。它是字符(分隔符列表)。
标签: c string linked-list