Lesson 88 +10 XP

Pointers

Pointers

A pointer is a variable that stores the address of another variable. Pointers point to data.

Declaring a pointer

Use * in the declaration:

int x = 25;        // a normal int
int *p = &x;       // pointer that holds x's address

p doesn't hold the value 25; it holds where 25 lives.

Reading the address

printf("%p", p);          // the address of x
printf("%d", x);          // 25

Dereferencing with *

The * operator (dereference) goes to the address and reads the value:

printf("%d", *p);         // 25, the value at p's address

Summary

  • * in a declaration: "pointer to".
  • & gets an address.
  • * on a pointer: dereference, get the value.

TL;DR

  • A pointer stores an address, not a normal value.
  • Declare with int *p;.
  • p = address; *p = value at that address.
  • & takes an address; * reads through one.