james1194430
james1194430

Reputation: 33

c++ making an array null using foreach

Node* nodes[3];

for (Node* eachNode:nodes) {
    eachNode = 0; //if i try to dereference it gives seg fault
}                 // eg. *eachNode = 0;

if (nodes[0] == 0) {
    cout << "Null";
} else
    cout << "Not null";

cout << '\n';

Node* nodes2[3];

for (int i = 0; i < 3; ++i) { //this way works fine
    nodes2[i] = 0;
}

if (nodes2[0] == 0) {
    cout << "Null";
} else
    cout << "Not null";

Hi guys I am trying to make all my objects in an array equal to null. When using a for loop it works fine but when I use a foreach loop it breaks.

The output i get is

Not null

Null

I think i have to dereference the nodes in the foreach loop but it gives a seg fault.

Does anyone know whats wrong? thanks.

Upvotes: 2

Views: 519

Answers (3)

Rulle
Rulle

Reputation: 4901

The loop you wrote loops over the values of the array:

for (Node* eachNode:nodes) {
    eachNode = 0;
}

The above loop could as well have been written using auto:

for (auto eachNode:nodes) {
    eachNode = 0;
}

The problem with the above loops is that eachNode is not the pointer stored in the array, but a copy of that pointer stored in a local variable of the loop.

If you wish to set the node to null, you need a reference to the memory location where you want to set it. You get that reference by referring to the array element using auto&:

for (auto& eachNode:nodes) {
    eachNode = 0;
}

This last segment will likely do what you want.

Upvotes: 5

user6f6e65
user6f6e65

Reputation: 146

Pointers are passed by value. So setting the eachNode = 0; will change the value, otherwise you are trying to dereference sonething that isn’t a pointer.

Upvotes: 0

jacob
jacob

Reputation: 4956

I believe instead you should try:

for(Node *&eachNode : nodes) {
    eachNode = nullptr;
}

This way you get a reference as opposed to the value, and you can appropriately set it to nullptr.

I'm not super experienced in C++ 11, but I did have a read here for more information about this new range construct.

Upvotes: 2

Related Questions