Swap with Pointers in C
Level 5199 keystrokes
Defines a swap function that receives the addresses of two ints and exchanges the values stored there. Because it works through pointers, x and y in main really change: 10, 20 before the call and 20, 10 after.
C code
// Takes two int pointers, so it can change the caller's variables1void swap(int *a, int *b) { // Saves the value at address a (10) in a temporary variable2 int temp = *a; // Copies the value at address b (20) to address a3 *a = *b; // Writes the saved value (10) to address b, completing the swap4 *b = temp;5}6 // Program entry point7int main() { // Declares the two values to swap8 int x = 10, y = 20; // Prints Before: x=10, y=209 printf("Before: x=%d, y=%d\n", x, y); // Passes the addresses of x and y with &, not their values10 swap(&x, &y); // The values are now exchanged: prints After: x=20, y=1011 printf("After: x=%d, y=%d\n", x, y); // Returns 0 to report that the program ended normally12 return 0;13}Output
Before: x=10, y=20 After: x=20, y=10
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this C code and how often they appear.
,× 9=× 9;× 8*× 6(× 5)× 5"× 4%× 4:× 2{× 2