danche
danche

Reputation: 1815

How to initialize an array of pointer inside a struct by using struct constructor?

I tried memset like

struct TreeNode {
    bool exist;
    bool word_ending;
    TreeNode* branches[3];
    TreeNode(): exist(true), word_ending(false) {
        memset(branches, NULL, sizeof(branches));
    }
};

but there appears warnings

warning: implicit conversion of NULL constant to 'int' [-Wnull-conversion]
        memset(branches, NULL, sizeof(branches));
        ~~~~~~           ^~~~
                         0
1 warning generated.

Is there some other way to initialize the array of pointer to NULL?

Upvotes: 1

Views: 134

Answers (1)

NathanOliver
NathanOliver

Reputation: 180510

Instead of using memset we can initialize the array in the member initialization list. If we use

TreeNode(): exist{true}, word_ending{false}, braches{} {}

Then braches will be zero initialized. This works because each missing initializer in a initialization list causes the corresponding element to zero initialized.

Upvotes: 4

Related Questions