When you aren't sure about something, start by asking yourself "what would happen if it was different?"
In this case, "what would happen if it was a pointer to a char that was passed?"
What your code is doing is swapping two pointers, so that the variables
str1
and
str2
"swap strings". But in C, all parameters are passed by value, not reference - which means that a copy of the value is passed to the function. So any changes you make to the parameter variables inside the method you call does not affect the outside world at all - the changes affect only the copy of the value, not the original variable:
void swap1(char **str1_ptr, char **str2_ptr)
{
char *temp = *str1_ptr;
*str1_ptr = *str2_ptr;
*str2_ptr = temp;
}
void swap2(char *str1_ptr, char *str2_ptr)
{
char* temp = str1_ptr;
str1_ptr = str2_ptr;
str2_ptr = temp;
}
int main()
{
printf("Hello\n");
char *str1 = "geeks";
char *str2 = "forgeeks";
swap1(&str1, &str2);
printf("str1 is %s, str2 is %s\n", str1, str2);
swap2(str1, str2);
printf("str1 is %s, str2 is %s\n", str1, str2);
getchar();
return 0;
}
The output is the same for both
printf
calls because the values passed are copies of the pointers and the changes are discarded when the
swap2
function exits.
So to change the outside world pointers, you need to pass a pointer to the pointer to the function!