自引用C结构
你能在C语言中有一个结构,它的元素是相同的吗?我在C中实现二叉搜索树的第一次尝试如下:自引用C结构,c,pointers,struct,self-reference,C,Pointers,Struct,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.v
#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;
}
#包括
结构二叉树节点{
int值;
结构二进制树节点*left=null;
结构二进制树节点*right=null;
};
main(){
结构二叉树节点t;
t、 数值=12;
结构二叉树节点y;
y、 数值=44;
t、 左=&y;
}
我不知道这段代码有什么问题,如果有任何帮助,我们将不胜感激。我意识到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’
首先,在C中,您的null
是null
。
其次,不能在结构定义中为结构中的元素设置值
所以,它看起来像这样:
#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;
}
#包括
结构二叉树节点{
int值;
结构二叉树节点*左;
结构二叉树节点*右;
};
main(){
结构二叉树节点t;
t、 左=空;
t、 右=空;
t、 数值=12;
结构二叉树节点y;
y、 左=空;
t、 右=空;
y、 数值=44;
t、 左=&y;
}
或者,您可以创建一个函数,使左侧和右侧为空
#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;
}
#包括
结构二叉树节点{
int值;
结构二叉树节点*左;
结构二叉树节点*右;
};
void make_null(结构二进制树节点*x){
x->left=NULL;
x->right=NULL;
}
main(){
结构二叉树节点t;
使_为空(&t)
t、 数值=12;
结构二叉树节点y;
使_为空(&y);
y、 数值=44;
t、 左=&y;
}
删除结构声明中的=null
。您可以声明自引用,但不能对其进行设置。定义结构时,不能在结构内部定义值。此代码段可能会使您的项目受益:
typedef struct binary_tree_node
{
int value;
binary_tree left;
binary_tree right;
} binary_tree_node, *binary_tree;
#define DATA(T) ((T)->value)
#define LEFT(T) ((T)->left)
#define RIGHT(T) ((T)->right)
错误消息是怎么说的?它说“error:'struct binary_tree_node'没有名为'left'的成员”,但我从定义中删除了“=null”,它至少现在正在编译。第一个错误的行通常是整个问题的关键。