自引用C结构

时间:2011-04-25 21:45:02

标签: 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.value = 12;

    struct binary_tree_node y;
    y.value = 44;
    t.left = &y;
}

我无法弄清楚这段代码有什么问题,任何帮助都会受到赞赏。我意识到在C中有关于二进制搜索实现的其他问题,但我试图用我自己的代码从头开始解决这个问题(当然还有一些指导)。谢谢!

3 个答案:

答案 0 :(得分: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’

首先,你null在{C} 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;
}

或者,您可以创建一个左右虚函数,

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

答案 1 :(得分:7)

删除struct声明中的= null。您可以声明自引用,但不能设置它。

答案 2 :(得分: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)