Pointer to Pointer...

This is a discussion on Pointer to Pointer... within the C++ Programming forums, part of the General Programming Boards category; I'm still new to programming and right now I'm having a little trouble understanding how pointer to pointer works. Can ...

  1. #1
    Registered User
    Join Date
    Oct 2002
    Posts
    5

    Pointer to Pointer...

    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).

  2. #2
    Registered User
    Join Date
    Aug 2002
    Location
    Hermosa Beach, CA
    Posts
    446
    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;
    }

  3. #3
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685
    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;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Following CTools
    By EstateMatt in forum C Programming
    Replies: 5
    Last Post: 06-26-2008, 10:10 AM
  2. Quick Pointer Question
    By gwarf420 in forum C Programming
    Replies: 15
    Last Post: 06-01-2008, 03:47 PM
  3. Parameter passing with pointer to pointer
    By notsure in forum C++ Programming
    Replies: 15
    Last Post: 08-12-2006, 07:12 AM
  4. Direct3D problem
    By cboard_member in forum Game Programming
    Replies: 10
    Last Post: 04-09-2006, 03:36 AM
  5. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21