Passing Pointer by pointer versus pointer by reference

Posted on 2006-04-07
Last Modified: 2012-05-05
I want to pass a pointer to a function which will modify the original pointer, i.e., I don't want to pass by value.  I read some tutorials and it seems you can either do something like:

void func1(char*& p) { p+=3; }

int main() {
      char* p = "ABCDEFG";
      cout << p << endl;

OR you can do:

void func1(char** p) { p+=3; }

int main() {
      char* p = "ABCDEFG";
      cout << p << endl;

Now, the first one works fine, and prints out "DEFG", showing that the original pointer has moved upwards.  But, the second one doesn't work.  It prints out "ABCDEFG", indicating that the original pointer has not moved at all.

It doesn't really matter to me which one I use, as they seem to both do the exact same thing.  I just was wondering why the second one doesn't work.  (I've seen the second tactic implemented before, like in the C library function wcstol.)  So, why isn't it working in my above example?
Question by:chsalvia
    LVL 20

    Accepted Solution

    the code for the second must be:

    void func1(char** p) { (*p)+=3; }

    LVL 20

    Expert Comment

    you changed the value in the local pointer ... but you want to change the value where p points too ...

    Featured Post

    Threat Intelligence Starter Resources

    Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

    Join & Write a Comment

    Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
    Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
    The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.
    The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

    731 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    15 Experts available now in Live!

    Get 1:1 Help Now