Pointers and functions
Read · 1 of 4
Give the function the address
A function gets copies of its arguments, so swap(a, b) can't swap a and b. Pass their addresses instead: swap(&a, &b), with void swap(int *x, int *y). Inside, *x is main's a.
That's exactly why scanf needs &: it has to write into your variable.
The same trick lets a function return several results: pass pointers to where each answer should go.
Read this lesson as text
Pass an address so a function can change the caller's variables, or hand back more than one result.
Give the function the address
A function gets copies of its arguments, so swap(a, b) can't swap a and b. Pass their addresses instead: swap(&a, &b), with void swap(int *x, int *y). Inside, *x is main's a.
That's exactly why scanf needs &: it has to write into your variable.
The same trick lets a function return several results: pass pointers to where each answer should go.
A swap that works
#include <stdio.h>
void swap(int *x, int *y) {
int t = *x;
*x = *y;
*y = t;
}
int main() {
int a = 3, b = 8;
swap(&a, &b);
printf("%d %d\n", a, b);
return 0;
}- Line 10: a is 3, b is 8.
- Line 11: Pass the addresses of a and b.
- Line 4: x points at a, y at b. Save *x (3) in t.
- Line 5: Write b's value into a: a is now 8.
- Line 6: Write the saved 3 into b.
- Line 12: Back in main, a and b really changed.
Exercise: Fix swap()
swap() should swap main's two numbers, but nothing changes. Fix the function and the call.
Exercise: Two answers from one function
Complete void minMax(int a[], int n, int *lo, int *hi) so it stores the smallest and largest of the array in *lo and *hi. main prints them.