7.3 Pointers and Functions
Why pointer parameters are needed
C passes arguments by value: when a function is called, the argument values are copied into the parameters. So a function that tries to swap two variables like this fails — it only swaps its own local copies.
void swap_wrong(int a, int b) {
int temp = a;
a = b;
b = temp; // swaps copies only; the caller's variables are unchanged
}Pass the addresses instead, and the function can modify the caller's variables through pointers:
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main(void) {
int x = 3, y = 5;
swap(&x, &y);
printf("%d %d\n", x, y); // 5 3
return 0;
}&x takes the address of x, and *a reaches the value at that address, so the swap really acts on x and y.
Returning several results through pointers
A function can return at most one value. To hand back several results, pass the addresses of variables as parameters and let the function write results back through the pointers.
void divmod(int a, int b, int *q, int *r) {
*q = a / b;
*r = a % b;
}
int main(void) {
int q, r;
divmod(17, 5, &q, &r);
printf("%d ... %d\n", q, r); // 3 ... 2
return 0;
}The same idea solves the quadratic equation ax² + bx + c = 0: use the return value to say whether real roots exist, and use pointers to carry back the two roots.
#include <math.h>
#include <stdbool.h>
bool solve(double a, double b, double c, double *x1, double *x2) {
double delta = b * b - 4 * a * c;
if (delta < 0) {
return false; // no real roots
}
*x1 = (-b + sqrt(delta)) / (2 * a);
*x2 = (-b - sqrt(delta)) / (2 * a);
return true;
}The caller first checks the returned bool, then reads the results from x1 and x2.