Summary

In this lesson, you learned that:

  • Every variable is stored in memory and has an address. &x is the address of the variable x, and %p prints it.
  • A pointer is a variable that holds an address: int *p = &x;. Its type says what it points to: int *, double *, char *.
  • *p is the value p points to (dereferencing). You can read it, printf("%d\n", *p);, and change it, *p = 20;. Without the star, p = &y; changes where the pointer points.
  • In a declaration, * makes a pointer. Before a pointer, it gets the value from the address. Between two values, it multiplies. & and * are opposites.
  • A function with a pointer parameter can change the caller's variable: void add_bonus(int *points, int bonus), called as add_bonus(&score, 5). A forgotten & in the call is a compile error; a forgotten * inside the function is a bug without any error.
  • Through pointers, a function can swap two variables or give back several results at once (output parameters).
  • The name of an array is the address of its first element, so int *p = numbers; and p[1] work. A parameter int numbers[] is a pointer, the same as int *numbers. That's why a function changes the caller's array and needs its count.
  • NULL is a pointer that points nowhere. A function that returns a pointer, such as the address of an element it found, returns NULL when there is none. Check a pointer that can be NULL before you use it: if (p != NULL). Reading through NULL stops the program here with RuntimeError: unreachable.
  • const int *numbers is a pointer that the function only reads through. Text in quotes gets a const char * pointer: const char *name = "Anna";.

In the next lesson, on structures, you'll learn to group values that belong together, such as a student's name and points, into one variable. Pointers will come in handy there too.

Instructions

Let's practice. The array scores holds the results of a test, and the teacher adds a bonus to each one. Above main, write a function add_bonus with the parameters int *scores, int count and int bonus. It adds the bonus to every score, but no score may go over 100 points: a higher one becomes 100. Call it with the bonus 10 before the loop. The program prints 55, 82, 100, 48 and 76, one per line.

Below add_bonus, write a function find_min_max with the parameters const int *scores, int count, int *lowest and int *highest. Through the two pointers, it stores the lowest and the highest score, so it gives back two results at once. Start by storing the first element in both. At the end of main, create two variables, pass their addresses to the function and print them: Lowest: 48, highest: 100.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

11/11