0

I got a struct defining a node for a tree data structure:

struct Node {
  int data;
  struct Node *children[10];
}

Given that children is NOT a dynamic array, I would like to initialize each pointer of children to NULL, but what follows doesn't work:

struct Node {
  int data;
  struct Node *children[10]={NULL};
}

Is there any workaround?

MadHatter
  • 638
  • 9
  • 23
  • 2
    Please include your actual code in the question. `struct *Node children[10];` is a syntax error. (Struct members cannot have initializers.) – Keith Thompson May 04 '15 at 16:12
  • If by some chance you are working with a C++ compiler, you can add a constructor to your `struct` which initializes all the member fields. – abelenky May 04 '15 at 16:14
  • Ok my syntax error was actually a typo. Corrected. And no, I cannot use a C++ compiler. – MadHatter May 04 '15 at 16:32
  • Please accept my apologies, after my last comment I was left without internet connection. All useful answers, I upvoted them all. Probably I should go with designated initializers. – MadHatter May 05 '15 at 22:25

3 Answers3

2
struct Node {
  int data;
  struct Node *children[10];
} a = {.children = {0}};

a is a struct Node object with all element of children member initialized to a null pointer.

ouah
  • 142,963
  • 15
  • 272
  • 331
2

This

 struct *Node children[10];  

is wrong. I would not even compile. It should be

 struct Node *children[10];  

To initialize all elements of member children to NULL you can use designated initializers.

struct Node {
  int data;
  struct Node *children[10];
} node = {.children = {NULL}};
haccks
  • 104,019
  • 25
  • 176
  • 264
1

You can't initialize data in the description of the struct because no memory has been allocated yet.

Let's look at the two styles of allocation you'll see:

The Stack

struct Node my_node = {
    0,
    {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL}
};

Or, because unlisted values will default to 0...

struct Node my_node = {};

The Heap:

Here, are only option is to null out the memory. We could use calloc() to do this since the memory it returns is zeroed out.

struct Node *my_node = calloc(1, sizeof(*my_node));

Or, we can explicitly use memset():

struct Node *my_node = malloc(sizeof(*my_node));
memset(my_node, 0, sizeof(*my_node));

Notes:

I'm generally assuming that NULL == 0. This isn't necessarily true. If you'd like to read more about these (mostly) historical systems: When was the NULL macro not 0?

If you're on one of those systems, or you're concerned about your code working on those platforms, then I would recommend using the first method (and most explicit) method that I described. It will work on all platforms.

Community
  • 1
  • 1
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173