dva*_*ria 3 c struct pointers self-reference
你能在C中有一个具有相同结构元素的结构吗?我在C中实现二叉搜索树的第一次尝试如下:
#include <stdio.h>
struct binary_tree_node {
int value;
struct binary_tree_node *left = null;
struct binary_tree_node *right = null;
};
main() {
struct binary_tree_node t;
t.value = 12;
struct binary_tree_node y;
y.value = 44;
t.left = &y;
}
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚这段代码有什么问题,任何帮助都会受到赞赏.我意识到在C中有关于二进制搜索实现的其他问题,但我试图用我自己的代码从头开始解决这个问题(当然还有一些指导).谢谢!
这是gcc 4上的错误消息:
test.c:6: error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token
test.c: In function ‘main’:
test.c:18: error: ‘struct binary_tree_node’ has no member named ‘left’
Run Code Online (Sandbox Code Playgroud)
首先,你null是NULL在C.其次,你不能在值在结构定义内的结构设置为一个元件.
所以,它看起来像这样:
#include <stdio.h>
struct binary_tree_node {
int value;
struct binary_tree_node *left;
struct binary_tree_node *right;
};
main() {
struct binary_tree_node t;
t.left = NULL;
t.right = NULL;
t.value = 12;
struct binary_tree_node y;
y.left = NULL;
t.right = NULL;
y.value = 44;
t.left = &y;
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以创建一个函数来使左和右NULL,
#include <stdio.h>
struct binary_tree_node {
int value;
struct binary_tree_node *left;
struct binary_tree_node *right;
};
void make_null(struct binary_tree_node *x) {
x->left = NULL;
x->right = NULL;
}
main() {
struct binary_tree_node t;
make_null(&t)
t.value = 12;
struct binary_tree_node y;
make_null(&y);
y.value = 44;
t.left = &y;
}
Run Code Online (Sandbox Code Playgroud)