Reading Through a Pointer

A pointer knows where a variable is. To get the value from that box, write * before the pointer: *p means "the value that p points to". Getting a value from an address is called dereferencing a pointer.

#include <stdio.h>

int main(void) {
    int age = 15;
    int *p = &age;
    printf("%d\n", *p);
    printf("%d\n", *p + 1);
    return 0;
}

This prints:

15
16

*p is an int, so you print it with %d and calculate with it like with any whole number.

& and * are opposites. & asks "where is it?" and turns a variable into its address. * asks "what's there?" and turns an address back into the value. That's why *&age is just age again.

A pointer doesn't keep a copy of the value. It knows only the address, and *p looks into the box every time. So when the variable changes, *p gives the new value:

int age = 15;
int *p = &age;
age = 16;
printf("%d\n", *p);

This prints:

16

The star has three meanings now. What matters is where it stands:

  • In a declaration, after a type: int *p = &age; creates a pointer. Here the star says "p is a pointer".
  • Before a pointer, anywhere else: *p is the value it points to.
  • Between two values: price * 2 is multiplication, as always.

So *p * 2 means "the value p points to, times two". The first star gets the value from the address, the second one multiplies.

The typical mistake is forgetting the star. Then you work with the address instead of the value, and the compiler tells you:

  • printf("%d\n", p); ends with the error format specifies type 'int' but the argument has type 'int *': %d expects an int, but p is an address.
  • p * 2 ends with the error invalid operands to binary expression ('int *' and 'int'). Operands are the values around an operator, here p and 2, and you can't multiply an address.

Instructions

The program doesn't compile. Read the error message and fix the last printf so that it prints the value p points to, not the address. The program prints Score: 50 and Through the pointer: 50.

Below it, print twice the score, again through the pointer: the text Doubled: and *p * 2. The program prints Doubled: 100 on the next line.

Below that, change the score directly, without the pointer: score = 60;. Then print the text Now: and *p. The pointer gives the new value: Now: 60.

Start programming for free

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

Or sign up with:

3/11