[英]Recursive structure (binary tree): obtain values via struct pointer from inside function
I'm on a mission to implement a basic binary tree. 我的任务是实现基本的二叉树。 Nodes of the tree are structures holding three fields, an integer value and pointers to the left and right children: 树的节点是包含三个字段,一个整数值以及指向左子元素和右子元素的指针的结构:
typedef struct node {
int value;
struct node *child_left;
struct node *child_right;
} node;
A new node structure is initialised as: 新的节点结构初始化为:
node node_init(int value, node *child_left, node *child_right) {
node k = {value, child_left, child_right};
return k;
}
A function to store a value inside a left child of the parent node: 将值存储在父节点的左子节点内的函数:
int insert_left(node *t, int value) {
node k = node_init(value, NULL, NULL);
if (t->child_left == NULL) {
t->child_left = &k;
}
else {
k.child_left = t->child_left;
t->child_left = &k;
}
}
A function to print out value of a left child (This is where the problem is): 一个输出左孩子的值的函数(这是问题所在):
int node_print(node k) {
printf("%d", k.child_left->value);
}
Main function to test the basic binary tree: 测试基本二叉树的主要功能:
int main(int argc, char* argv[]) {
node root = node_init(7, NULL, NULL);
insert_left(&root, 3);
printf("%d\n", root.child_left->value);
node_print(root);
}
Running this example a direct call to the printf()
correctly prints 3 as a value of the left child, but the node_print()
outputs a value of the address of the pointer, eg -406140704. 运行此示例,直接调用printf()
正确打印3作为左子node_print()
的值,但是node_print()
输出指针地址的值,例如-406140704。
This may be a common and ubiquitous problem, but how do I correctly access the value
field from inside of the node_print()
function? 这可能是一个普遍存在的问题,但是如何从node_print()
函数内部正确访问value
字段呢? If possible, please direct me to some explanatory reading. 如果可能的话,请引导我阅读一些解释性读物。
Your init function uses a local variable which is not available anymore once the function returns. 您的init函数使用局部变量,该局部变量一旦函数返回就不再可用。 Change it to: 更改为:
node *node_init(int value, node *child_left, node *child_right) {
node *k = malloc(sizeof(*k));
k->value= value;
k->child_left= child_left;
k->child_right= child_right;
return k;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.