gpt4 book ai didi

c - 为什么我会收到这段代码的段错误?

转载 作者:行者123 更新时间:2023-11-30 14:39:16 30 4
gpt4 key购买 nike

我正在使用 C 构建一棵树,但我的 addNode() 函数出现段错误。

我怀疑这是因为我将一个子元素分配给了 NULL 指针,但情况似乎并非如此。

//This is the tree node struct.
struct NODE {
int value;
struct NODE* child_list;
struct NODE* right_sibling;
struct NODE* parent;
};


//This function adds a node to an element in the tree with a value equal to parent value.
struct NODE* addNode (struct NODE* existing, int parentVal, int childVal) {
struct NODE* child = existing;
struct NODE* child_right = child->right_sibling;

while (child != NULL) {
if (child->value == parentVal) {
struct NODE* new = malloc(sizeof(struct NODE));
new->value = childVal;
new->parent = child;
new->right_sibling = child->child_list;
child->child_list = new;

break;
}
while (child_right != NULL) {
if (child_right->value == parentVal) {
struct NODE* new_sibling = malloc(sizeof(struct NODE));
new_sibling->value = childVal;
new_sibling->parent = child_right;
new_sibling->right_sibling = child->child_list;
child_right->child_list = new_sibling;
break;
}
child_right = child_right->right_sibling;
}
child = child->child_list;
}


return existing;
}

//Here is the implementation of the function that I used to test the function.

int main () {

struct NODE* root = malloc(sizeof(struct NODE));
root->value = 100;
root->child_list = NULL;
root->right_sibling = NULL;
root->parent = NULL;

root = addNode(root, 100, 7);
root = addNode(root, 100, 10);
root = addNode(root, 100, 15);
root = addNode(root, 7, 30);
root = addNode(root, 15, 20);
root = addNode(root, 15, 37);

printTree(root);


return 0;
}

程序应该打印一棵具有正确子级的树,但我在运行代码时收到了段错误。

最佳答案

很明显,在创建新节点时,我没有在 while 循环中将 child_list 设置为 NULL。感谢Retired Ninja提出解决方案!

关于c - 为什么我会收到这段代码的段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56160331/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com