FatalKeystroke
FatalKeystroke

Reputation: 3062

How do I initialize a pointer in a struct to null in C++11?

Here's my struct:

struct node {
    int load;
    int tolerance;
    bool has_fired;
    node *in[1];
    node *out[1];
    };

I've tried:

node mynode;

mynode->in = null;
mynode->in = nullptr;
mynode->in = &nullptr;
mynode->in = 0;
mynode->in = false;

I really don't know what's wrong, I remember the first assignment USED to work but not anymore apparently. Any help?

EDIT: In the actual source file 'mynode' is a pointer inside of another struct.

Upvotes: 1

Views: 4324

Answers (4)

Kerrek SB
Kerrek SB

Reputation: 477434

Like this perhaps:

struct node
{
    int load;
    int tolerance;
    bool has_fired;
    node *in[1] = { nullptr };
    node *out[1] = { nullptr };
};

(Note that node::in and node::out are arrays of pointers.)

Usage:

node n;    // n.in and n.out are initialized

In C++11 the brace-or-equal-initializer makes the class a non-aggregate. If that's a problem, you can also omit the initializer and say:

node n;
n.in[0] = nullptr;
n.out[0] = nullptr;

Or even:

node n { 0, 0, false,  { nullptr }, { nullptr } };

Upvotes: 5

bames53
bames53

Reputation: 88215

This is assignment rather than initialization. Since in is an array of pointers you have to set the array element to null. Also mynode is not a pointer, so you don't use the arrow operator.

mynode.in[0] = nullptr;

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409404

Create a constructor?

struct node
{
    node()
        : in{{ nullptr }}, out{{ nullptr }}
    {}

    ...
};

Upvotes: 0

juanchopanza
juanchopanza

Reputation: 227498

Try value initialization:

node mynode{};

This will value-initialize all the members, which for built-ins and PODS means zero initializaiton.

Upvotes: 4

Related Questions