自引用 C 结构
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;
}
我无法弄清楚这段代码有什么问题,任何帮助将不胜感激。我意识到关于 C 中的二分搜索实现还有其他问题,但我试图用我自己的代码(当然还有一些指导)从头开始解决这个问题。谢谢!
Can you have a structure in C that has elements of that same structure? My first attempt at implementing a binary search tree in C is the following:
#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;
}
I can't figure out what's wrong with this code, any help would be appreciated. I realize there are other questions on binary search implementations in C, but I'm trying to figure this out from scratch with my own code (and some guidance of course). Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
删除结构声明中的
= null
。您可以声明自引用,但不能设置它。Remove the
= null
in your struct declaration. You can declare the self-reference, but you cannot set it.这是 gcc 4 上的错误消息:
首先,您的
null
是 C 中的NULL
。其次,您不能为结构定义内的结构中的元素设置值。
所以,它看起来像这样:
或者,您可以创建一个函数来使 left 和 right 为 NULL,
This is the error message on gcc 4:
Firstly, you
null
isNULL
in C.Secondly, you cannot set a value to an element in a struct inside the struct definition.
So, it would look something like this:
Or, you can create a function to make left and right NULL,
定义结构体时不能定义结构体内部的值。此代码片段可能会使您的项目受益:
You cannot define the values inside the struct when defining the struct. This code snippet may benefit your project: