feded
feded

Reputation: 139

Simple Struct definition in C for Red Black Tree

I don't use the C language since years and now I need it again. I'm trying to build a Red-Black Tree but I'm stuck at the beginning because I'm missing something about "structs".

Take a look to my "structs" declarations please, they are easy. This is a header file included in Red_black_tree.c

 #define BLACK 0 //defalut color
#define RED 1 //

struct Node {  //create a black node by default, to have a red one look at "create_red_node"
    struct Node *left = NULL;
    struct Node *right= NULL;
    int key = 0;
    int value = 0;
    char color = BLACK;
};

struct Root_t {
    struct Node* Root;
};

struct Node* create_node () {
    struct Node* black = (Node*) malloc (sizeof(Node));
    return black;
}

struct Node* create_red_node () {
    struct Node* red = create_node ();
    red->color=RED;
    return red;
}

Root_t* create_tree () {
    struct Root_t* fake=(Root_t*) malloc (sizeof(Root_t));
    struct fake->Root->left=create_red_node ();
    struct fake->Root->right=create_red_node ();
    return fake;
}

I compiled with "gcc Red_black_tree.c -o RBTree". GCC says something like : "expected ';' at end of declaration list" 7 times, or "must use 'struct' tag to refer to type... ", "expected identifier...". What do you think, is it good to create RBTree?

Upvotes: 0

Views: 188

Answers (1)

David Ranieri
David Ranieri

Reputation: 41017

In C, you can not assign while you define the members of a struct

Instead of

struct T {
    int a = 1;
    int b = 2;
};

you need something like

struct T {
    int a;
    int b;
};
...
struct T t = {.a = 1, .b = 2};

In addition, all your members are set to 0 (NULL is an alias of (void *)0), when you want to allocate memory and initialize all to zero at the same time you can use calloc

struct Node* black = calloc(1, sizeof(*black)); // Dont cast malloc and friends

And here:

struct fake->Root->left=create_red_node();

, you don't want the struct keyword, instead:

fake->Root->left=create_red_node();

Another suggestion: do not hardcode the data of the red-black-tree in the structure, (int key, value;) even if it works you end up with a non reusable container, instead, use a generic pointer to void (void *data;) and a callback to your comparison functions in the implementation.

struct Node *insert(struct Node *root, int (*comparer)(const void *, const void *)) ...

Upvotes: 2

Related Questions