I made a code to swap two strings:
void swap (char *a, char *b)
{
char *t = a;
a = b;
b = t;
}
int main()
{
char * strings[2];
strings [0] = "luck!";
strings [1] = "good ";
swap (strings[0], strings[1]);
printf( "%s %s\n",strings[0], strings[1]);
return 0;
}
And it fails. What i have trouble understanding is when i call swap() i pass two pointers. Both pointers point to the first character of their assigned arrays. I then created a temporary pointer inside the function and perform basic switch. What is flawed here? I really want to understand why this approach is wrong?
You are switching the parameters of the function, which are local to the function scope. When your function is executed, the parameters (a, of type char*, and b, of type char*) are passed by value, put on the stack, and the function is executed. The parameters are modified and then popped of the stack without effect.
To make a difference, you need to pass references to the parameters:
and then call with:
You now pass pointers to individual array elements in
strings, which is in main’s stack segment and thereby persists past the context ofswap.