1

_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

0

2 Answers 2

4

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();
Sign up to request clarification or add additional context in comments.

3 Comments

You answer another one of my questions, thanks :) In C would using ** and dereferencing everywhere be the only option?
Second try, i have to learn to read ;) Yes, sadly in C there are no real aliases.
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).
-1

_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

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.