Pointers: &, *, and pass-by-pointer
Handout
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
A problem from last lesson
- Last lesson, a function got a copy of your number. Changing the copy did not change the original.
- C copies every argument you pass to a function. So a normal function cannot change your variable.
- To change it, the function needs the variable's address — where it lives in memory.
Every variable has an address
- Think of a variable as a box in memory. The value is kept inside the box.
- Every box has an address: a number that says where the box is.
- The
&operator gives you that address.&xmeans "the address ofx".
A pointer holds an address
- A pointer is a variable that stores an address, not a normal value.
- You declare one with a
*:int *p = &x;reads as "ppoints tox". - To reach the value at that address, put
*in front:*p. This is called dereference. - Changing
*pchanges the original variable.*p = 5;puts5intoxitself.
#include <stdio.h>
void set_to_five(int *p) {
*p = 5; // change the value at the address
}
int main(void) {
int x = 0;
set_to_five(&x); // pass the ADDRESS of x
printf("%d\n", x); // 5 — the original changed!
return 0;
}
Out-pointers: giving back more than one answer
- A function can
returnonly one value. But it can change several variables through pointers. - You pass the address of each answer, like
find(&min, &max). The function writes into them with*. - These extra pointer parameters are called out-pointers. The caller reads the answers after the call.
- A pointer that points to nothing is
NULL. Never dereference aNULLpointer.
Now you try
- Each task gives you a function to complete. Use
*to read or change the value the pointer points to. - When a value comes in through a pointer (like
int *p), write your answer through it — do notreturnit. - Do not write a
main— the checker provides one. Press Run, then Check answer.
Complete void add_one(int *p) so it adds 1 to the int that p points at. Use *p. Do not write a main — the checker provides one.
Click Run to see the output here.
Complete void swap(int *a, int *b) so it exchanges the two ints. Use a temporary variable. Do not write a main.
Click Run to see the output here.
Complete void min_max(const int a[], int n, int *min_out, int *max_out). Scan the array, then write the smallest value through min_out and the largest through max_out. Assume n >= 1. Do not write a main.
Click Run to see the output here.