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 中的二进制搜索实现还有其他问题,但我试图用我自己的代码(当然还有一些指导)从头开始解决这个问题。谢谢!

4

3 回答 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’

首先,您nullNULLC 中。其次,您不能为结构定义内的结构中的元素设置值。

所以,它看起来像这样:

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

或者,您可以创建一个函数来使 left 和 right 为 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;
}
于 2011-04-25T21:50:13.647 回答
7

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

于 2011-04-25T21:50:21.167 回答
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)
于 2011-04-25T21:52:42.477 回答