Pointer Variables

An address is a value, just like a number. So you can store it in a variable. A variable that stores an address is called a pointer: it points to another variable, which means it tells you where that variable is.

int age = 15;
int *p = &age;

Read the second line like this: "p is a pointer to an int, and it holds the address of age". We say that p points to age. The * in the declaration says that p is a pointer. The int before it says what kind of value is in the box it points to.

Two boxes in memory. The box of the variable p, at the address 0xfff8, holds the address 0xfffc. An arrow leads from it to the box of the variable age, at the address 0xfffc, which holds 15. p points to age.

So the type of p is int *, "pointer to int". A pointer to a double has the type double *, and a pointer to a char has the type char *. Short names like p are common for pointers in small examples. C doesn't mind the spaces around the *: int *p, int* p and int * p mean the same. This course writes int *p.

A pointer is a variable too, so it has its own box with its own address. But what's in its box isn't 15. It's the address of age. When you print p with %p, you get the same number as for &age:

#include <stdio.h>

int main(void) {
    int age = 15;
    int *p = &age;
    printf("Address of age: %p\n", &age);
    printf("Value of p: %p\n", p);
    return 0;
}

This prints:

Address of age: 0xfffc
Value of p: 0xfffc

Common mistakes:

  • int *p = age; without & ends with the error incompatible integer to pointer conversion initializing 'int *' with an expression of type 'int'; take the address with &. A pointer holds an address, not a number like 15. The end of the message even tells you the fix: take the address with &.
  • The type of the pointer must fit the type of the variable. After double price = 9.5;, the line int *p = &price; ends with the error incompatible pointer types initializing 'int *' with an expression of type 'double *'. The address of a double belongs in a double *.

Instructions

Below the variable price, create a pointer p of type int * that points to temperature.

At the end of the program (before return 0;), print the value of p with %p: the text Value of p: and p. It's the same address as the one on the first line of the output.

Below the pointer p, create a second pointer q that points to price (q is a common name for a second pointer, as it comes after p). Choose its type yourself: what kind of value does price hold? Then, at the end of the program (before return 0;), print Value of q: and q.

Start programming for free

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

Or sign up with:

2/11