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 tim开发者_如何学JAVAe 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
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();
_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
精彩评论