开发者

Self-Referencing C Struct [duplicate]

This question already has answers here: Why can't we initialize members inside a structure? (6 answers) Closed 7 years ago.

Can you have a structure in C that has elements of that sa开发者_如何学运维me 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!


Remove the = null in your struct declaration. You can declare the self-reference, but you cannot set it.


This is the error message on 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’

Firstly, you null is NULL 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:

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

Or, you can create a function to make left and 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;
}


You cannot define the values inside the struct when defining the struct. This code snippet may benefit your project:

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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜