Example 1 — Swap two integers
Both values live in main; swap edits them through pointers.
#include <stdio.h>
void swap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}
int main(void) {
int x = 3, y = 9;
printf("before: x=%d y=%d\n", x, y);
swap(&x, &y);
printf("after: x=%d y=%d\n", x, y);
return 0;
} How It Works
&xand&ypass the addresses.*aand*bname the original variables.- The three assignments swap the stored values.
