Search

Search papers and lessons

Pointer

Level 1 · 12 min read

A pointer is a variable whose value is the address of another value in memory, so a program can reach that value indirectly, share it between parts of the code, and build structures whose shape changes while it runs.

On this page

  • Colour = topic mix
  • Algorithms
  • Systems
  • Discrete math
  • ReadReady to readNot yet

TL;DR

Every value a program uses lives in some numbered place in memory, and that number is its address. A pointer is a variable whose value is such an address, so instead of holding the data itself it says where the data is. Following the pointer to the data is called dereferencing. Pointers let two parts of a program share one value, and they let a program link pieces of data together in chains whose length changes as it runs.

Builds on: Binary Numbers (Bits and Bytes) for how an address is stored as a number, and Array for the idea that memory has positions · Leads to: Linked List (a chain of nodes joined by pointers), binary trees, and the rules for freeing memory in Garbage Collection

Where it's used

Linked structures. Most of the data structures in a typical program are built from pointers. A Linked List node holds a value and the address of the next node. A binary tree node holds a value and the addresses of its two children. A hash table often keeps each bucket's chain of entries as pointers. The shape of these structures can change at any moment, because adding a node only means writing one new address.

Operating systems. When a program asks for memory, the operating system does not hand over the memory itself. It hands back an address, and every later access goes through that address. The same idea appears one level down, where the processor's own instructions carry addresses that point at the next instruction or at data, and where Virtual Memory maps the addresses a program sees onto physical memory.

Shared state in a graphical app. A text editor might keep one document object, and several windows each hold a pointer to it. When the user types, the document changes once, and every window that follows the pointer sees the new text. Copying the whole document into each window would give stale copies that disagree.

How it works

Think of memory as a long row of numbered boxes. Each box holds one value and has an address, which is just its number. To keep the example small, this toy machine uses boxes that each hold one whole number, and a pointer is also stored in one box.

Suppose box 100 is an integer variable x and box 104 is a pointer variable p. Start with both empty.

  1. Store a value in x. Write 42 into box 100. Now x holds 42. Check: box 100 holds 42, and nothing else has changed.

  2. Store the address of x in p. The address of x is 100, so write 100 into box 104. Now p holds 100. It does not hold 42. Check: box 104 holds 100, which is a location, not the data.

  3. Dereference p. Read what p holds, which is 100. Go to box 100 and read what is there, which is 42. The pointer led the program to the value. Check: p points to box 100, and box 100 holds 42.

flowchart LR
  P["Read p from box 104: it holds 100"] --> G["Go to box 100"]
  G --> V["Read the value there: 42"]
  1. Change the value through the pointer. Go to the box that p names, box 100, and write 7 there. Now x holds 7, because x and the box p names are the same box. Check: reading x directly now gives 7, and so does dereferencing p.

  2. Move the pointer. Suppose box 108 is another integer y that holds 5. Write 108 into box 104. Now p points at y, and x still holds 7. Check: changing p changed where it leads, but not the boxes themselves.

The key steps are 2 and 3. A pointer stores a location, and using it means one extra jump. The program reads the pointer, then reads the place it names.

The math

Definition: Pointer

A pointer is a variable pp whose value is an address aa. If the address aa names a stored value vv, then pp refers to vv. Reading the value through the pointer is written ∗p\ast p and gives vv.

The formal version mirrors the steps above. Write addr(x)\text{addr}(x) for the address of a variable xx.

Step 2 in symbols: storing an address

p=addr(x)=100p = \text{addr}(x) = 100

The assignment copies the number 100 into pp. The value of pp is a number like any other, and it is stored in a box of its own, here box 104.

Step 3 in symbols: dereferencing

∗p=contents of box p=contents of box 100=42\ast p = \text{contents of box } p = \text{contents of box } 100 = 42

This is two reads, one of the pointer and one of its target. Every dereference costs at least one extra memory access compared with using a variable directly.

Step 4 in symbols: writing through a pointer

∗p←7so thatx=7\ast p \leftarrow 7 \quad \text{so that} \quad x = 7

Writing through the pointer changes the box that xx names, which is why xx changes too.

How big is an address?

An address is a number, and its size limits how much memory a program can reach.

A 32-bit pointer can name 232=4,294,967,2962^{32} = 4{,}294{,}967{,}296 different bytes, about 4 gigabytes. A 64-bit pointer can name 2642^{64} bytes, about 1.8×10191.8 \times 10^{19}, which is far more memory than any machine holds today. On a 64-bit machine a pointer takes 8 bytes, which is why the toy machine above, where addresses take 4 bytes, is only a model.

Pointer arithmetic: moving through an array

A pointer can carry that address and move by whole elements. If pp holds the address of element ii, then p+kp + k names element i+ki + k, and the address moves by k⋅sk \cdot s bytes. In symbols, addr(p+k)=addr(p)+k⋅s\text{addr}(p + k) = \text{addr}(p) + k \cdot s. This is why an array and a pointer into it are so closely related in languages like C.

Worked examples

Example
Example 1: reading and changing through a pointer (tiny)

Box 100 holds the integer x, which is 3. Box 104 holds the pointer p, which is 100.

  1. Dereference p: go to box 100 and read 3. So *p is 3.
  2. Compute *p = *p + 1. The right side reads 3 and adds 1, giving 4.
  3. Write 4 into the box that p names, which is box 100. So x is now 4.
  4. The pointer itself is unchanged: box 104 still holds 100.

Interpretation: the write went to box 100, because the pointer's value was 100. Only the target changed. A pointer's own value changes only when you assign to the pointer.

Example
Example 2: walking an array with a pointer (standard)

Let the array a be [7, 2, 9, 4, 6] with base address 200, and let each element take 4 bytes. Set pp to the address of element 0, which is 200.

  1. Element 0 is at 200+0⋅4=200200 + 0 \cdot 4 = 200. Dereferencing pp gives 7.
  2. Compute p+2p + 2. This is 2 elements further on, so the address is 200+2⋅4=208200 + 2 \cdot 4 = 208.
  3. Dereference p+2p + 2: box 208 holds 9. So *(p + 2) is 9, which is a[2].
  4. To visit every element, add one element at a time: p+1p + 1 is at 204 and holds 2, p+2p + 2 is at 208 and holds 9, p+3p + 3 is at 212 and holds 4.
  5. The pointer advances by 4 bytes each step because each element is 4 bytes. The program never computes a position from scratch, it just moves pp.

Interpretation: a pointer into an array is the same address arithmetic as the Array lesson, with the index replaced by a step along the pointer.

Example
Example 3: a linked list in memory (realistic)

A linked list of one million integers stores each node as a 4-byte value and an 8-byte pointer to the next node, on a 64-bit machine.

  1. Each node holds 4+8=124 + 8 = 12 bytes of data.
  2. For one million nodes the data is 1,000,000×12=12,000,0001{,}000{,}000 \times 12 = 12{,}000{,}000 bytes.
  3. In binary units that is 12,000,000÷1,048,576≈11.412{,}000{,}000 \div 1{,}048{,}576 \approx 11.4 mebibytes.
  4. The actual size is larger, because the machine pads nodes and its memory allocator keeps bookkeeping data for each block, but the pointers are the part that makes the structure grow in place.
  5. To find the 500th node, the program starts at the head and follows 499 pointers in turn. Each follow is a separate memory access, which is slower than reading an array index.

Interpretation: the list costs extra space for pointers and extra time to walk, in exchange for inserting and removing nodes without moving the others.

Try it: A linked list has 2,000 nodes, each 12 bytes of data as above. How many bytes of data does it hold?

Answer: 2,000×12=24,0002{,}000 \times 12 = 24{,}000 bytes.

Common mistakes and tradeoffs

It is tempting to think that a pointer is the value it points to. In fact a pointer holds an address, a number that says where the value is. Two pointers can lead to the same value, and changing the value is visible through both, because both lead to the same box.

It is tempting to think that a pointer and an array are the same thing. In fact an array is a block of values in consecutive boxes, and a pointer is a box holding an address. In C, an array name is often converted to a pointer to its first element, which hides the difference. The difference matters when you assign, copy, or ask for the length.

It is tempting to think that a pointer is always safe to use. In fact there are two common ways a pointer goes wrong. A null pointer holds a special address value that means "points to nothing", and dereferencing it crashes or reads garbage. A dangling pointer still holds the address of memory that has been freed and may have been reused for something else, so reading through it gives unrelated data, and writing through it corrupts that data.

It is tempting to think that pointers are only for experts. In fact the same few rules cover everything: store an address, follow it to read or write, and be sure the target still exists. Most bugs come from breaking the third rule.

When to use a pointer: you need to share one value between several parts of a program, or you need a structure whose size and shape change while it runs. When not to use one: the data is small and copying it is cheap, or a plain array indexed by position does the job. Pointer chasing also hurts speed, because nodes scattered through memory are slow to reach, as the Memory Hierarchy lesson explains. Alternatives: storing indices into an array instead of addresses, which avoids dangling addresses and keeps data together; or a garbage-collected language, where the runtime decides when a value is no longer reachable, so the program does not free anything by hand.

History

Early computers already named memory by number, so a program could refer to a location by its address. Pointers as a language feature came as high-level languages were built on top of that hardware. In 1965, Tony Hoare added a null reference to the ALGOL W language. He later described it as a costly mistake, because it has caused so many program crashes since.

The C language, developed at Bell Labs in the early 1970s, made pointers central. It let programmers do address arithmetic directly, which is why the same ideas still appear in systems code today. Its design made the trade plain: fast and close to the machine, but the programmer must keep every pointer valid.

Pointers caught on because they match the machine. A processor reads memory by address, so a language that exposes addresses gives the programmer direct control over that work. The cost, bugs from invalid addresses, drove later languages to add checks, managed references, and automatic memory reclamation.

Recap

  • Memory is a row of numbered boxes, and each value has an address.
  • A pointer is a variable whose value is an address, not the data itself.
  • Dereferencing a pointer reads the target, which costs one extra memory access.
  • Pointer arithmetic moves by whole elements, so a pointer into an array uses the same address formula as an index.
  • Pointers allow sharing and changing structures, at the cost of null and dangling pointer errors.

Read next: Linked List for a structure built entirely from pointers, binary tree for pointers that branch, and Garbage Collection for how managed languages free memory without the programmer tracking every pointer. Virtual Memory shows how the addresses a program sees map onto real memory.

Check yourself

QuestionWhat does a pointer store: the data it points to, or the address of the data?Show answer

It stores the address. The address says where the data is, and dereferencing the pointer is the step that reads the data at that address.

QuestionBox 300 holds the integer x, which is 11. Box 304 holds the pointer p, which is 300. What is x after the statement `*p = *p * 2`, and what does p hold?Show answer

Dereferencing p reads 11 from box 300, and 11×2=2211 \times 2 = 22 is written back to box 300. So x is 22. The pointer p still holds 300, because the statement changed only the box p names.

QuestionWhy does dereferencing a null pointer cause trouble, even though the pointer is just a number?Show answer

The number zero, or the special null value, does not name a real value. Following it means reading or writing a box that holds no data the program meant to use, so the program crashes or reads garbage. Checking a pointer for null before following it prevents this.

QuestionA 64-bit program has an array of 1,000 values, each 8 bytes, starting at address 4000. Let q be a pointer to element 0. What address does q + 10 hold?Show answer

Each step moves by one element of 8 bytes, so q + 10 moves 10×8=8010 \times 8 = 80 bytes. The address is 4000+80=40804000 + 80 = 4080.

Sources

Pointer — explained simply · ungoon.me