Why doesn't the pointer to a char * string change when the string changes in this function?
I wrote a simple function to perform a place reversal:
void in_place_reverse(char *str){
if(!str || !(*str)){
return;
}
char *str_end = str+strlen(str)-1;
int temp;
while(str < str_end){
temp = *str;
*(str++) = *str_end;
*(str_end--) = temp;
}
}
I'm just wondering why when I do something like this:
char str[] = "Reverse me!";
cout << "Original: " << str << endl;
in_place_reverse(str);
cout << "Reversed: " << str << endl;
str
has not been changed inside the function. The reason I am asking is because the string *(str++)
increments the pointer pointing to str
. So I'm really asking why something like this isn't needed:
char *str_beg = str;
char *str_end = str+strlen(str)-1;
int temp;
while(str_beg < str_end){
temp = *str_beg;
*(str_beg++) = *str_end;
*(str_end--) = temp;
}
So we don't actually change the pointer pointing to the first position str
.
source to share
You are really doing this implicitly because 'str' is passed by value (read: 'as a copy in a temporary variable).
To clarify this without a (distracting) pointer: consider
void increment(int x) {
x++;
}
int i = 1;
cout << i << endl;
increment(i);
cout << i << endl;
This will print '1' twice. x
that is displayed inside the subroutine increment
has the same meaning as passed i
. But this is not the same variable i
. This is actually a copy i
. When we return from the routine, the copy is discarded. Further reading: It would be different if we passed x
by reference, for example:
void increment(int &x) {
x++;
}
source to share
A function declaration void in_place_reverse(char *str)
causes the pointer created when the function is called to be copied into a named variable str
that is private and local to in_place_reverse. You can change this value however you like without affecting the original, which exists in the scope of the calling function.
source to share