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
In place of the first comment, write a function swap with two parameters of type int *, a and b, that swaps the values they point to.
In main, in place of the comment between the first two printf lines, call swap with the addresses of first and second. The program prints 3 8 and then 8 3.
In place of the second comment, write a function sort_pair that also gets two pointers to int. When the first one points to a bigger number than the second one, it calls swap to swap them, so the smaller number always ends up first. Then, in place of the last comment, call sort_pair with the addresses of x and y. The last line of the output is then 4 9.
Start programming for free
6/11