尝试实现二叉树时的分段错误



我正在尝试在C++中实现二叉树结构。我想要一棵深度为"8"的树,即我想要一个具有 1 个attribute_node和 2 个指向其他 2 个attribute_struct的指针的attribute_struct来制作二叉树。这是我定义的数据结构及其创建方法:

struct person{
    public :
        char name[20];
};
struct attribute_node{
    int attribute;
    person * child_person;
};
struct attribute_struct{
    attribute_node head_node;
    attribute_struct * yes_node;
    attribute_struct * no_node;
};
attribute_struct initialize_struct(attribute_struct initial_struct, int prop){
    if(prop < 8){
        attribute_struct new_yes_struct, new_no_struct;
        attribute_node temp_yes_node, temp_no_node;
        temp_yes_node.attribute = prop;
        temp_yes_node.child_person = NULL;
        temp_no_node.attribute = prop;
        temp_no_node.child_person = NULL;
        new_yes_struct.head_node = temp_yes_node;
        new_no_struct.head_node = temp_no_node;
        new_yes_struct.yes_node = NULL;
        new_no_struct.yes_node = NULL;
        new_yes_struct.no_node = NULL;
        new_no_struct.no_node = NULL;
        attribute_struct temp_yes_struct = initialize_struct(new_yes_struct, prop+1), temp_no_struct = initialize_struct(new_no_struct, prop+1);
        initial_struct.yes_node = &temp_yes_struct;
        initial_struct.no_node = &temp_no_struct;
        return initial_struct;
    }else{
        person temp_person;
        strcpy(temp_person.name, "temp");
        initial_struct.head_node.child_person = &temp_person;
        return initial_struct;
    }
}
attribute_struct create_initial_attribute_structure(){
    attribute_struct main_structure;
    attribute_node temp_node;
    temp_node.attribute = 3;
    temp_node.child_person = NULL;
    main_structure.head_node = temp_node;
    main_structure.yes_node = NULL;
    main_structure.no_node = NULL;
    main_structure = initialize_struct(main_structure, 1);
    return main_structure;
}

好吧,当我尝试使用如下所示的结构时,我遇到了分段错误。

int main(){
    attribute_struct main_struct = create_initial_attribute_structure();
    attribute_struct * current_head;
    current_head = &main_struct;
    int iter = 0;
    while(iter < 7){
        current_head = (*current_head).yes_node;
        cout << iter << endl;
        iter++;
    }
    return 0;
}

无法确定数据结构是否创建错误,或者我是否以错误的方式引用它。我使用了 gdb,但由于它在主函数中没有参数,我无法推断出任何东西。

那么 seg 故障是在打印 iter 2 之后。那么,如何确定定义的attibute_struct是否正确且深度为 8 级,或者我是否引用了 NULL 对象?使用 if(current_head == NULL) cout <<"错误";在 while 循环中没有帮助。

您正在调用create_initial_attribute_structure,它将yes_node设置为 NULL

然后current_head设置为 yes_node 这是空

然后下一次迭代你去引用current_head

您正在取消引用空

最新更新