I'm still new to programming and right now I'm having a little trouble understanding how pointer to pointer works. Can someone give me an explanation (a sample code would be great too).
Printable View
I'm still new to programming and right now I'm having a little trouble understanding how pointer to pointer works. Can someone give me an explanation (a sample code would be great too).
A pointer to a pointer is usually used when you want to update the address of a pointer. Why would you want to do this, you may ask? Well, sometimes you want the user of a function to provide you with a pointer to some data type, and you will return via that pointer malloc'ed memory to something. To be honest, I'm not sure how necessary this is in C++...usually you see this sort of thing in c code.
But...here's an example, which assumes the existence of some type SomeDataType, with a member function DoSomething. But hopefully you get the idea:
Code:int main()
{
SomeDataType* pSomeData = NULL;
SomeDataTypeAllocator(&pSomeData);
// we should have a valid pointer now
if (pSomeData)
pSomeData->DoSomething();
SomeDataTypeFree(pSomeData);
return 0;
}
void SomeDataTypeAllocator(SomeDataType** pData)
{
if ( pData )
*pData = new SomeDataType();
}
void SomeDataTypeFree(SomeDataType* pData)
{
if ( pData )
delete pData;
}
I tend to agree with IfYouSaySo. In C++ you would usually use references to pointers instead of pointers to them.
Code:void some_func(int *&someptr) {
someptr = new int;
}