tags:

views:

132

answers:

2
+1  Q: 

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

+5  A: 

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();
Georg Fritzsche
You answer another one of my questions, thanks :) In C would using ** and dereferencing everywhere be the only option?
Winder
*Second try, i have to learn to read ;)* Yes, sadly in C there are no real aliases.
Georg Fritzsche
You _could_ use a macro in C,`#define a (_stuckVertices[ (row * _cols) + colnum ])`, you'd just need to be careful with it (well you have to be careful with the reference too, but for slightly different reasons, and in different ways).
Logan Capaldo
A: 

_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

Valentin Heinitz
You ignore the assigment of the new instance in both cases, which is the real problem.
Georg Fritzsche