mathieu_b
mathieu_b

Reputation: 393

Initialize a structure with NULL values

I have a problem when I'm initializing this structure :

struct node {
    int label;
    struct node *lchild;
    struct node *rchild;
}

int main(void) {
    struct node n1;
    n1.label = 1;

    return EXIT_SUCCESS;
}

The problem is my members lchild and rchild don't point to NULL.

I can resolve the problem by adding

n1.lchild = NULL;
n1.rchild = NULL;

But I don't understand why I need to do that?

Upvotes: 1

Views: 4576

Answers (2)

alk
alk

Reputation: 70911

I don't understand why I need to do that

Because the compiler doesn't do it for you.

You could skip this in case you can make sure the members aren't read before having been written to.

Upvotes: 7

juanchopanza
juanchopanza

Reputation: 227390

The members of an automatic storage object such as n1 do not get zero-initialized automatically (See C11 standard, 6.7.9.10). You have to do this yourself.

You can take care of this easily by suitably initializing n1:

struct node n1 = {1};

This will set the first member to 1 and will zero-initialize the rest, meaning the pointers get initialized to NULL. You can be more explicit if you wish:

struct node n1 = {1, NULL, NULL};

References:

From the C11 standard, 6.7.9 Initialization:

  1. If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

And, previously in the same section,

  1. ... If an object that has static or thread storage duration is not initialized explicitly, then:
    — if it has pointer type, it is initialized to a null pointer;

(emphasis mine)

Upvotes: 7

Related Questions