Neezo
Neezo

Reputation: 9

can't set an identifier of type struct to nullptr;

I have a struct that looks like this:

struct Wolf {
    Wolf *dog;
    Wolf *puppy;
};

I have written:

Wolf *alphawolf = new Wolf;

when I try to set the members dog and puppy to nullptr, it doesn't compile in C++

UPDATE:

I tried:

alphawolf.dog = nullptr;
alphawolf.puppy = nullptr;

alphawolf and the . is underlined red: The error is:

this declaration has no storage class or type specifier

Now I used:

alphawolf->dog = nullptr;
alphawolf->puppy = nullptr;

But I am trying to do this before the main method, "outside main()" I still get: this declaration has no storage class or type specifier

Upvotes: 0

Views: 78

Answers (1)

Jack C.
Jack C.

Reputation: 774

It is not possible to put executable statements outside of main() (or any other function).

If you want to declare a global variable alphawolf, with initial values of nullptr, the syntax is (outside of main()):

Wolf alphawolf {nullptr, nullptr};

It is also possible to allocate a global Wolf* with new. To initialize it, the syntax is:

Wolf *alphawolf = new Wolf {nullptr, nullptr};

To assign nullptr to alphawolf's members, the statements need to be inside main(), or some other function.

Wolf *alphawolf = new Wolf;
int main() {
    alphawolf->dog = nullptr;
    alphawolf->puppy = nullptr;

    /* Do other stuff with alphawolf */

    return 0;
}

Upvotes: 2

Related Questions