Swapping Two Variables
Swapping the values of two variables is a common task in programming, for example when sorting. In main, without a function, it looks easy at first:
int a = 3;
int b = 8;
a = b;
b = a;
printf("%d %d\n", a, b);This prints:
8 8The line a = b; overwrote the original value of a, the 3, and it was lost. It's like swapping the drinks in two full glasses: you need a third, empty glass. In a program, that glass is a helper variable, where you first store the original value of a:
int a = 3;
int b = 8;
int temp = a;
a = b;
b = temp;
printf("%d %d\n", a, b);This prints:
8 3A function swap has to change two variables of its caller, so both parameters must be pointers: void swap(int *a, int *b). Inside, it does the same three steps as above, only with *a and *b instead of a and b. The helper variable temp stays an ordinary int, because it holds a value, not an address. The call passes two addresses: swap(&x, &y);.
Watch out for these mistakes:
- When you forget the stars (
int *temp = a; a = b; b = temp;), the function swaps the two pointers, its own copies of the addresses. The program compiles and runs, but the variables inmainstay as they were. - A function that already has pointers passes them on without
&. Inside a function with the parametersint *aandint *b, you callswap(a, b), becauseaandbalready are addresses.swap(&a, &b)ends with the errorincompatible pointer types passing 'int **' to parameter of type 'int *'; remove &.int **is the address of a pointer, which you don't need here, and the message tells you what to do: remove the&.
Instructions
- 1
In place of the first comment, write a function
swapwith two parameters of typeint *,aandb, that swaps the values they point to. - 2
In
main, in place of the comment between the first twoprintflines, callswapwith the addresses offirstandsecond. The program prints3 8and then8 3. - 3
In place of the second comment, write a function
sort_pairthat also gets two pointers toint. When the first one points to a bigger number than the second one, it callsswapto swap them, so the smaller number always ends up first. Then, in place of the last comment, callsort_pairwith the addresses ofxandy. The last line of the output is then4 9.