Swap function
- Why does the following swap function not work?
? ? ? ? It's important to note that when we pass arguments from one to another, those arguments are copied from one function to another. Therefore, the two arguments x, y, are copied into a, b, but it only works well within the swap function without touching the original values.?
void swap( int a, int b );
int main(void)
{
? ? ? ? int x = 1;
? ? ? ? int y = 2;
? ? ? ? swap( x, y );
? ? ? ? printf("x: %i, y: %i\n", x, y);
}
void swap( int a, int b )
{
? ? ? ? int temp = a;
? ? ? ? a = b;
? ? ? ? b = temp;
}
? ? ? ? Again check the diagram of the memory layout, the stack is loaded from the bottom up.
For the stack space,?
????????Swap Function (on top of main with local variables a, b, temp)
????????Main Function (at the very bottom of the stack with variables x, y)
Once the swap function completes executing and returns, that chunk of memory essentially goes away (see stack). More specifically,?
Used by local variables and functions in our programs as we are called, which will be auto-discarded.?Those functions don't physically disappear but become garbage values after execution, and the memory they were using is freed for the next function call.?
- Improvement: using pointers to modify original values
void swap( int *a, int *b );
int main(void)
{
? ? ? ? int x = 1;
? ? ? ? int y = 2;
? ? ? ? swap( &x, &y );
? ? ? ? printf("x: %i, y: %i\n", x, y);
}
void swap( int *a, int *b )
{
? ? ? ? int temp = *a;
? ? ? ? *a = *b;
? ? ? ? *b = temp;
}