C分段故障函数参考

C分段故障函数参考,c,dictionary,cs50,C,Dictionary,Cs50,sizeH(node*ptr)函数上的if(ptr->is_word)导致分段错误 dictionary.c:120:13: runtime error: member access within null pointer of type 'node' (aka 'struct node') dictionary.c:120:13: runtime error: load of null pointer of type '_Bool' Segmentation fault 如果我添加一个If条

sizeH(node*ptr)
函数上的
if(ptr->is_word)
导致分段错误

dictionary.c:120:13: runtime error: member access within null pointer of type 'node' (aka 'struct node')
dictionary.c:120:13: runtime error: load of null pointer of type '_Bool'
Segmentation fault
如果我添加一个
If
条件以在该If条件之前返回一个特定值,那么代码将执行,并且我确保根不为null 所以我想问题在于
ptr
没有正确地传递给
sizeH
函数

unsigned int size(void)
{
    node *ptr = root;
    printf(ptr->is_word ? "true" : "false");
    unsigned int count = sizeH(ptr);
    printf("COUNTER IN SIZE %d\n" , count);
    return 0;
}

unsigned int sizeH(node *ptr){
    if(ptr->is_word)
    {
        return 1;
    }
    else
    {
        for(int x = 0; x < N; x++){
            return 0 + sizeH(ptr->children[x]);

        }
    }
    return 0;
}
无符号整数大小(void)
{
node*ptr=root;
printf(ptr->is_word?“true”:“false”);
无符号整数计数=sizeH(ptr);
printf(“计数器大小为%d\n”,计数);
返回0;
}
无符号整数sizeH(节点*ptr){
如果(ptr->is_word)
{
返回1;
}
其他的
{
对于(int x=0;xchildren[x]);
}
}
返回0;
}

您的
sizeH
函数有几个基本问题。首先,它不检查传入的
ptr
是否为
NULL
。这很可能发生,因为您的函数是递归的,并且您有为每个子节点调用的循环

    for(int x = 0; x < N; x++){
        return 0 + sizeH(ptr->children[x]);

    }

选择一种编码格式样式并坚持使用,而不是混合使用,因为这样可以使代码更整洁

您可以调用sizeH(NULL)。编辑代码以包含
节点
结构。编辑代码以显示如何分配
根目录。通常只需添加可以编译的代码。请显示一个。由于某种原因,
root
可能是
NULL
。您的错误消息与代码不匹配(第120行不存在)。
unsigned int sizeH(node *ptr) {
    if(ptr==NULL) {
        return 0;
    } else if(ptr->is_word) {
        return 1;
    } else {
        unsigned int ret = 0;
        for(int x = 0; x < N; x++) {
            ret += sizeH(ptr->children[x]);
        }
        return ret;
    }
    // return 0; This isn't needed - the code will never reach here.
}