DMarlon Studio

Lesson 15 · 15 of 20

Pointers: address and value · C

Learn what a pointer is in C: a variable's address with &, its value with *, functions that change the caller's variables, and NULL.

C · Pointers: address and value in DMarlon Studio: the example's code and its output in the terminal

Every variable lives at a place in memory with an address. The `&` operator gives that address, and a pointer is a variable that stores it: int *p = &score; declares p as a "pointer to int" and makes it point at score. The address changes from one run to the next, so the example only checks that p == &score.

The ***** operator in front of a pointer goes to that address: *p is the value of score, 50. It can change it too: after *p = 75, score is 75, because p and score refer to the same place.

Here is what makes pointers so useful. Lesson 13 showed that a function gets copies; if it gets an address instead, it can change the original variable. add_points(&score, 25) adds 25 to score, and swap exchanges gold and silver. That is exactly what scanf does with &age in lesson 5.

`NULL` is a pointer that points to nothing. Before using * on a pointer that might be NULL, check it: reading *nowhere would crash the program.

Code · main.c

#include <stdio.h>// With a pointer, a function can change the caller's variable.void add_points(int *score, int points) {    *score += points;}void swap(int *a, int *b) {    int tmp = *a;    *a = *b;    *b = tmp;}int main(void) {    int score = 50;    int *p = &score;  // & gives the address; p stores it    // The address changes from run to run, so we only compare it.    printf("p points to score: %s\n", p == &score ? "yes" : "no");    printf("score = %d, *p = %d\n", score, *p);    *p = 75;  // * follows the address and changes the value there    printf("after *p = 75, score = %d\n", score);    add_points(&score, 25);    printf("after add_points, score = %d\n", score);    int gold = 3, silver = 8;    swap(&gold, &silver);    printf("after swap: gold = %d, silver = %d\n", gold, silver);    int *nowhere = NULL;  // NULL: points to nothing, check before use    if (nowhere == NULL) printf("nowhere is NULL\n");    return 0;}

Output · cc main.c -o main && ./main

p points to score: yes
score = 50, *p = 50
after *p = 75, score = 75
after add_points, score = 100
after swap: gold = 8, silver = 3
nowhere is NULL

Key points

  • &x gives the address of x.
  • int *p is a pointer to an int.
  • *p reads or changes the value it points to.
  • With a pointer, a function can change the caller's variables.
  • Check that a pointer is not NULL before using it.

Exercise

Write void split_bill(double total, int people, double *each, double *tip) that stores what each person pays and a 10% tip, and print both values from main.