How to initialize a const variable inside a struct in C?
If you are using C99, you can used designated initializers to do this:
struct Tree t = { .root = NULL, .NIL = &t.NIL_t };
This only works in C99, though. I've tested this on gcc and it seems to work just fine.
For those seeking a simple example, here it goes:
#include <stdio.h>
typedef struct {
const int a;
const int b;
} my_t;
int main() {
my_t s = { .a = 10, .b = 20 };
printf("{ a: %d, b: %d }", s.a, s.b);
}
Produces the following output:
{ a: 10, b: 20 }
A structure defines a data template but has no data itself. Since it has no data, there's no way to initialize it.
On the other hand, if you want to declare an instance, you can initialize that.
struct Tree t = { NULL, NULL, NULL };