我正在解决 K&R 书籍 (#6.3) 中的一个问题,其中用户输入了一系列单词,您必须创建这些单词的列表以及每个单词出现的行。它应该涉及结构,所以这些是我现在拥有的:
struct entry {
int line;
int count;
struct entry *next;
};
struct word {
char *str;
struct entry *lines;
struct word *next;
};
static struct word *wordlist = NULL; // GLOBAL WORDLIST
但是,当我输入一些内容并且程序尝试向结构中添加一个新条目(有点像链表)时,出现了问题,程序终止并且没有错误消息。代码:
void add_entry(char *word, int line)
{
if (word == NULL || line <= 0 || is_blocked_word(word))
return;
struct word *w;
for (w = wordlist; w != NULL && w->next != NULL && !strcmp(w->str, word); w = w->next);
// If word is found in the wordlist, then update the entry
if (w != NULL) {
struct entry *v;
for (v = w->lines; v != NULL && v->next != NULL && v->line != line; v = v->next);
if (v == NULL) {
struct entry *new = (struct entry*) malloc(sizeof(struct entry));
new->line = line;
new->count = 1;
new->next = NULL;
if (w->lines == NULL)
w->lines = new;
else
v->next = new;
}
else v->count++;
}
// If word is not found in the word list, then create a new entry for it
else {
struct word *new = (struct word*) malloc(sizeof(struct word));
new->lines = (struct entry*) malloc(sizeof(struct entry));
new->next = NULL;
new->str = (char*) malloc(sizeof(char) * strlen(word));
new->lines->line = line;
new->lines->count = 1;
new->lines->next = NULL;
strcpy(new->str, word);
// If the word list is empty, then populate head first before populating the "next" entry
if (wordlist == NULL)
wordlist = new;
else
w->next = new;
}
}
即使在仅将第一个单词添加到wordlist
. 这是在说明if (wordlist == NULL) wordlist = new;
wherenew
包含指向我 malloc'ed 的有效结构的指针的行上。这怎么可能?
据我所知,这是我的指针使用问题,但我不确定它到底在哪里。有人可以帮忙吗?