Thursday, 19 September 2013

How to initialise a pointer to a pointer when the final address isn't known?

How to initialise a pointer to a pointer when the final address isn't known?

In this example, I'd like to pass a pointer pointer to the future,
not-yet-allocated someObject to a function. (Please don't ask why.)
int main(void) {
functionThatNeedsSomeObject();
SomeClass someObject(0);
}
I'm trying to do that using a pointer to a pointer. This is my attempt:
int main(void) {
SomeClass** ppSomeObject;
functionThatNeedsSomeObject( ppSomeObject);
SomeClass someObject(0);
*ppSomeObject = &someObject;
}
But in my code, ppSomeObject is uninitialized when it is passed. Of course
the second-layer pointer can't point to the object, but how can I make the
first-layer pointer point somewhere that I can change later, when
someObject is created?
Should I do something like this? Even if it works, creating an
intermediate pointer feels unnecessary.
SomeClass* pSomeObject = 0;
SomeClass** ppSomeObject = &pSomeObject

No comments:

Post a Comment