Winder
Winder

Reputation: 1984

C++ Pointer Issue

_stuckVertices is an array of pointers and I would like to update one index of that array without using _stuckVertices[ (row * _cols) + column ] 3 times. The reason it is an array of pointers is because the vast majority of the time the pointer will be NULL. The following code works but I need to dereference a each time I use it:

void Cloth::stickPoint(int column, int row)
{
    Anchor **a = &_stuckVertices[ (row * _cols) + column ];
    if (!*a)
        *a = new Anchor(this, column, row);
    (*a)->stick();
}

I originally had it written like this, but the _stuckVertices pointer doesn't get updated:

void Cloth::stickPoint(int column, int row)

    {
        Anchor *a = _stuckVertices[ (row * _cols) + column ];
        if (!a)
            a = new Anchor(this, column, row);
        a->stick();
    }

Is there a way to write Anchor *a = _stuckVertices[ index ] so that a is like an alias into the array that I can update, or is something like the first piece of code how I should do this?

Thanks

Upvotes: 1

Views: 167

Answers (2)

Valentin H
Valentin H

Reputation: 7448

_stuckVertices is an array of pointers

What do you mean by this? Did oyu created it like this: Anchor *_stuckVertices = new Anchor[Number]; or like this: Anchor *_stuckVertices[Number]={0}; ?

In first case you should be able to do this:

Anchor *a = _stuckVertices +((row * _cols) + column);
a->stick();

In second case:

Anchor *a = _stuckVertices[((row * _cols) + column)];
a->stick();

And just a hint, (row * _cols) + column could be bigger then array-length You should at least add an assertion before accessing _stuckVertices e.g.:

#include <cassert>
assert (sizeof(_stuckVertices)/sizeof(_stuckVertices[0]) > ((row * _cols) + column) );

Regards, Valentin Heinitz

Upvotes: -1

Georg Fritzsche
Georg Fritzsche

Reputation: 98984

References are what you are looking for - they are aliases:

Anchor*& a = _stuckVertices[ (row * _cols) + column ];
if (!a)
    a = new Anchor(this, column, row);
a->stick();

Upvotes: 4

Related Questions