3

Can you have a structure in C that has elements of that same 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!

Shweta
  • 5,198
  • 11
  • 44
  • 58
dvanaria
  • 6,593
  • 22
  • 62
  • 82

3 Answers3

7

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;
}
Dhaivat Pandya
  • 6,499
  • 4
  • 29
  • 43
7

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

Brian L
  • 10,757
  • 5
  • 19
  • 17
0

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)
Evan Mulawski
  • 54,662
  • 15
  • 117
  • 144