refrence to a pointer

This is a discussion on refrence to a pointer within the C++ Programming forums, part of the General Programming Boards category; given a pointer type * ptr; When or why would you pass the pointer by refrence to a function ie ...

  1. #1
    Registered User
    Join Date
    Jul 2003
    Posts
    450

    refrence to a pointer

    given a pointer
    type * ptr;
    When or why would you pass the pointer by refrence to a function ie
    function(&ptr);
    Instead of simply passing the address directly
    function(ptr);

    I saw this done and don't understand why.

    The prototype for the pass by refrence example
    was
    function(type **ptr);
    A pointer to a pointer. I do not understand.

  2. #2
    Registered User
    Join Date
    Dec 2003
    Posts
    5
    if the function wanted to change the pointer and not the referenced data it would need to be passed a pointer to the pointer.

  3. #3
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,655
    Remember that, like any other variable, a pointer itself has an address in memory. When you pass a pointer to a function, a copy of it is made. This copy obviously has a different address than the original. That's why you can do:

    Code:
     void print(char * s)
    {
        while(*s != 0)
       {
         cout << *(s++);
       }
    
     cout << endl;
    }
    The original pointer is unaffected.

    Now let's say you wanted to write a function in C that increments a pointer. You would have to do:

    Code:
     void inc(char ** p)
    {
     *(p++);
    }
    With C++, it's simply more readable (and less typing) to use:

    Code:
     void inc(char * & p)
    {
     p++;
    }

  4. #4
    Registered User
    Join Date
    Jul 2003
    Posts
    450
    I got it so given
    type *ptr
    ptr is the address of the data the pointer points to or in other words is refrenced by
    and
    &ptr is the address of the pointer which in turn refrences some data.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 03-24-2008, 10:16 AM
  2. Parameter passing with pointer to pointer
    By notsure in forum C++ Programming
    Replies: 15
    Last Post: 08-12-2006, 07:12 AM
  3. Direct3D problem
    By cboard_member in forum Game Programming
    Replies: 10
    Last Post: 04-09-2006, 03:36 AM
  4. How did you master pointers?
    By Afrinux in forum C Programming
    Replies: 15
    Last Post: 01-17-2006, 07:23 PM
  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