chsalvia
asked on
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?
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?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
you changed the value in the local pointer ... but you want to change the value where p points too ...