c - 单词出现次数和行号

标签 c

我正在编写一个程序,该程序生成一个文本文件,其中包含单词的出现次数以及另一个文本文件每次出现的行号。我正在使用一个 AVL 树结构,其中包含单词和一个链表结构,其中每个行号包含一个节点。以下是结构体定义:

struct llnode {
    struct llnode *next;
    int num;
};
struct node {
    char *word;
    struct llnode *head;
    struct node *left;
    struct node *right;
    int height;
};

当我尝试使用以下函数打印到文本文件时,出现段错误。

void listprint(struct llnode *p) {
    if(p->next == NULL) {
        printf("%d", p->num);
    } else {
        printf("%d, ", p->num);
        listprint(p->next);
    }
}
void treeprint(struct node *p) {
    if(p != NULL) {
        treeprint(p->left);
        printf("%s: ", p->word);
        listprint(p->head);
        treeprint(p->right);
    }
}

具体问题出在这一行

if(p->next == null) {

gdb 给我

Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000000

感谢您的帮助。

编辑:

void listinsert(struct llnode *p) {
struct llnode *prev = p;
while(p != NULL) {
    prev = p;
    p = p->next;
}
p = lalloc();
p->num = line;
p->next = NULL;
prev->next = p;

struct node *addtree(struct node *p, char *w) {
int cond;
if(p == NULL) {
    p = talloc();
    p->head = NULL;
    p->word = mystrdup(w);
    p->head = listinsert(p->head);
    p->left = p->right = NULL;
} else if((cond = strcmp(w, p->word)) == 0) {
    listinsert(p->head);
} else if(cond < 0) {
    p->left = addtree(p->left, w);
    if(height(p->left)-height(p->right) == 2) {
        if(strcmp(w, p->left->word) < 0) {
            p = singleleft(p);
        } else {
            p = doubleleft(p);
        }
    }
} else {
    p->right = addtree(p->right, w);
    if(height(p->right)-height(p->left) == 2) {
        if(strcmp(w, p->right->word) > 0) {
            p = singleright(p);
        } else {
            p = singleleft(p);
        }
    }
}
return p;

int getword(char *word, int lim) {
int c;
char *w = word;
while(isspace(c = getch()));
if(c == '\n') {
    line++;
}
if(c != EOF) {
    *w++ = c;
}
if(!isalpha(c)) {
    *w = '\0';
    return c;
}
for( ; --lim > 0; w++) {
    if(!isalnum(*w = getch())) {
        ungetch(*w);
        break;
    }
}
*w = '\0';
return word[0];

最佳答案

listprint中,在检查p->next是否为空之前,您不会检查p是否为空。

关于c - 单词出现次数和行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5454874/

相关文章:

c - 如何重置 C 中的结构条目

c - 如何通过UDP发送结构并在另一端接收?

c - 如何在不提示用户的情况下检测 Linux C GUI 程序中的按键?

c - 为什么这些构造使用增量前和增量后未定义的行为?

c - 我应该如何修复此快速排序功能?

c - #符号在C中是什么意思?

c++ - 如何存储图以最大化图约简算法的局部性?

检查 stdin 是否有待处理的字节(用于转义序列)

c - 如何使用 gettimeofday() 在 c/unix 中打印时间

c - 从列表中删除节点时出现问题