• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 282
  • Last Modified:

Passing Pointer by pointer versus pointer by reference

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";
      func1(p);
      cout << p << endl;
}

OR you can do:

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

int main() {
      char* p = "ABCDEFG";
      func1(&p);
      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?
0
chsalvia
Asked:
chsalvia
  • 2
1 Solution
 
ikeworkCommented:
the code for the second must be:

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


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

Featured Post

Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now