自引用C结构体

3

在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语言二分查找实现的问题,但是我正在尝试使用自己的代码(当然还有一些指导)从头开始解决这个问题。谢谢!


3
错误信息显示了什么? - samoz
它报错说“错误:'struct binary_tree_node'没有名为'left'的成员”,但是我从定义中移除了“= null”,现在至少能编译了。 - dvanaria
通常情况下,第一个错误的行号通常是解决整个问题的关键。 - Paul Nathan
3个回答

7
这是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语言中nullNULL。 其次,在结构体定义内部无法给结构体中的元素设置值。

因此,代码可能会像这样:

#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;
}

或者,你可以创建一个函数将左右两侧设置为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;
}

7

在你的结构声明中,去掉= null。你可以声明自引用,但不能设置它。


0

在定义结构时,不能在结构内部定义值。以下代码片段可能有助于您的项目:

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接