Skip to content
Tutorials Center
My learning

Topics

Lesson 45 of 135 ยท Pointers

Pointers

Learn C pointers from scratch - memory addresses, the & and * operators, printing with %p, dereferencing, NULL and C23 nullptr, and the bad pointers to avoid.

Every variable in a running C program lives somewhere in memory, and every byte of memory has a number called its address. A pointer is a variable that stores an address. Instead of holding a value like 42, it holds "the place where some int lives", and through that address you can read the int or change it.

Pointers are the feature that gives C its reputation, good and bad. They're how functions modify your variables (scanf("%d", &n) has been using one since your first input lesson), how arrays and strings are passed around, how programs use memory from the heap, and how linked lists and trees connect their pieces. They're also behind many famous crashes and security bugs, because a pointer can hold an address where there's nothing valid to read. This lesson builds a solid mental model step by step: addresses and the & operator, declaring pointers, dereferencing with *, null pointers (including C23's nullptr), and the kinds of bad pointers to watch out for.

The rest of this chapter builds on what you learn here: Pointer Arithmetic, Pointers and Arrays and more.

Memory and addresses

Picture memory as one very long row of numbered boxes, each holding one byte. A variable occupies one or more consecutive boxes: on our server an int takes 4, a double takes 8. The number of the first box is the variable's address.

The address-of operator & gives you that address. You print an address with the %p format specifier, which expects a void * (a generic pointer, covered in void Pointers), so you cast the address to (void *):

C Taking addresses with &

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The addresses are printed in hexadecimal, like 0x7ffd5c3e1a2c. Run the program twice and they change: modern operating systems place the stack at a random position on every run, a security feature called address space layout randomization (ASLR). So never write a program whose output depends on an exact address.

The last line shows that an address itself has a size. On a 64-bit system, addresses are 8 bytes, so &count is 8 bytes even though count is 4. The exact format of %p output is up to the C library; with glibc on Linux it's 0x followed by hex digits.

Declaring a pointer

A pointer variable is declared with a * between the type and the name. The type says what kind of object the pointer points to:

C
int *count_ptr;        /* a pointer to an int */
double *price_ptr;     /* a pointer to a double */
char *letter_ptr;      /* a pointer to a char */

Read int *count_ptr as "count_ptr is a pointer to int". Its type is written int *. To make it point somewhere, assign it an address of the matching type:

C
int count = 42;
int *count_ptr = &count;     /* count_ptr now holds count's address */

The pointed-to type matters. An int * must point to an int; assigning &price (a double *) to it is a type error that GCC 14 and later reject outright (initialization of 'int *' from incompatible pointer type 'double *'). The type is what tells the compiler how many bytes to read and how to interpret them when you follow the pointer.

Where the star goes

int *p, int* p and int * p are all the same to the compiler. Most C code writes int *p, with the star next to the name, and there's a reason: the star belongs to each variable in a declaration, not to the type as a whole.

C
int *a, b;       /* a is an int *, but b is a plain int! */
int *c, *d;      /* both are pointers */

Writing int* a, b; makes it look as if both are pointers, which is a classic misreading. Declaring one pointer per line avoids the question entirely.

Dereferencing: following the pointer

The dereference operator * goes the other way: given a pointer, *p is the object it points to. Not a copy, the object itself. You can read it, and you can assign to it:

C Reading and writing through a pointer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

After int *p = &level;, the expressions level and *p refer to the same box of memory. Assigning to either one changes both, because there's only one integer.

The last part shows the difference between changing the pointer and changing the pointee:

  • p = &other; changes which object p points to. level is untouched.
  • *p = 0; changes the object p points to, which is now other.

Watch the parentheses in (*p)++. Postfix ++ binds tighter than *, so *p++ would mean *(p++): move the pointer, not increment the value. You'll use that on purpose in Pointer Arithmetic; here it would be a bug.

Two meanings of * and &

Both symbols do different jobs depending on where they appear, which is confusing at first:

Symbol In a declaration In an expression
* int *p declares a pointer *p dereferences: the object p points to
* a * b multiplies
& (not used in C declarations) &x takes the address of x
& a & b is bitwise AND

* and & are opposites: *&x is just x, and &*p is just p (for a valid pointer).

Why pointers are useful

So far you could have used the variable directly. Pointers become essential when the code that wants to change a variable isn't the code that owns it. The simplest case is a function. C passes arguments by value, so a function gets copies; give it an address and it can reach the original:

C A function that changes your variable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

With the preset input 7, the program prints with bonuses: 22. Now scanf("%d", &score) makes sense: scanf must store the number in your variable, so it needs the address, exactly like add_bonus. Forgetting the & there is a classic beginner bug; GCC warns that %d expects an int * argument.

Pointers also let you work with arrays and strings without copying them, and they're the only way to use memory allocated at run time with malloc. You'll see those in Pointers and Arrays, Pointers and Functions and Dynamic Memory.

Null pointers: pointing at nothing

Sometimes a pointer has nothing valid to point to yet, or a function wants to say "not found". For that, C has the null pointer, a special value guaranteed not to be the address of any object. You can compare against it, but you must never dereference it.

There are three ways to write a null pointer:

  • NULL, a macro defined in <stddef.h>, <stdio.h>, <stdlib.h> and <string.h>. This is what most existing C code uses.
  • 0. A literal zero converts to a null pointer, so int *p = 0; is valid, but it reads like a number.
  • nullptr, a keyword added in C23. Its type is nullptr_t, and it can only become a pointer, never an integer, so it can't be confused with 0. Use it when your compiler supports C23 (ours does); use NULL for code that must build with older compilers.

A pointer converts to a truth value: a null pointer is false and any other pointer is true. So if (p) means if (p != NULL), and if (!p) means if (p == NULL).

C Using null pointers safely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Returning a pointer that might be null is a standard C idiom: the standard library does it in strchr, fopen, malloc and many more. The rule for callers is equally standard: check before you dereference. Notice that glibc prints a null pointer with %p as (nil); other libraries print 0x0 or 00000000.

You can write int *p = &values[i]; and then change values[i] through p because first_negative returns a pointer into the caller's array, which still exists after the function returns. Returning the address of a function's own local variable would not be safe, as you'll see in Pointers and Functions.

Dereferencing a null pointer is undefined behavior. On desktop systems it usually crashes immediately with a segmentation fault (signal SIGSEGV), because the operating system keeps the lowest addresses unmapped. On small embedded chips, address 0 may be real memory and the bug silently corrupts data. And since the compiler may assume a dereferenced pointer was never null, it's allowed to remove a later if (p == NULL) check. Always check before the *.

Bad pointers to avoid

A null pointer is the safe kind of invalid pointer, because you can test for it. Two other kinds look like perfectly normal addresses, so no test can catch them:

Uninitialized (wild) pointers. A local pointer that you declare without a value holds whatever bits were in that memory before. Using it reads or writes a random location:

C
int *p;          /* uninitialized: points who-knows-where */
*p = 5;          /* undefined behavior: may crash, may corrupt another variable */

GCC often warns about this ('p' is used uninitialized), but not in every case. The habit that prevents it: initialize every pointer when you declare it, to a real address or to NULL/nullptr.

Dangling pointers. A pointer that held a valid address, but the object there has since ended: a local variable of a function that returned, or heap memory that has been freed. The address hasn't changed, but what's there is no longer yours.

C
int *p = NULL;
{
    int temporary = 7;
    p = &temporary;
}                /* temporary's lifetime ends here */
/* *p is now undefined behavior, even though p still holds the same address */

Memory Errors shows how tools like AddressSanitizer and Valgrind catch these at run time. For now, the rule is simple: a pointer is only valid while the object it points to is alive.

Wild, dangling, null and void pointers compared

People often mix up these four terms, so here they are side by side. Three are hazards; the fourth, void *, is simply a useful type that is easy to misuse.

Kind What it is Can you test for it? Typical symptom
Wild Declared but never given a value, so it holds leftover bits No Random crashes or silent corruption
Dangling Was valid, but its object has ended (freed, or a local that went out of scope) No Garbage values, crashes, or "works on my machine"
Null Deliberately points to nothing (NULL/nullptr) Yes, if (p) Immediate segmentation fault if dereferenced
void * A pointer to some type, with the type forgotten n/a Compile error if dereferenced; wrong results if cast to the wrong type

The most useful thing to remember is the direction of safety: null is the only one of the bad states you can detect at run time. That is why the habits below all turn the other two into null.

  • Prevent wild pointers by initializing: int *p = NULL; or point it at a real object on the same line.
  • Prevent dangling pointers by clearing: after free(p), write p = NULL;. A second free(p) is then harmless, and a later if (p) check works. This does not protect other copies of the address, so with several pointers to one block, decide which one owns it.
  • Never return the address of a local variable, and never keep a pointer into a block that realloc may have moved (Dynamic Memory).
  • Treat void * as "typeless storage": convert it to the right type before dereferencing, and only to the type the object really has. In C the conversion is implicit; in C++ it needs a cast.
C Making the hazards safe

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Every pointer here is either null-checked or points at a live object, so the output is predictable. The void * lesson is what the compiler does not check: if you called show(&count, 'd'), you would pass the address of an int and claim it is a double. The type was erased, so the compiler cannot object; the program would read the wrong bytes (undefined behavior) and print nonsense. Typeless pointers push the responsibility for the type onto you.

What the tools say

You cannot test for wild or dangling pointers in code, but you can catch them while testing. Compile with -fsanitize=address -g and AddressSanitizer reports the bad access with where the memory was allocated and freed. These are read-only examples, because the browser runner does not use sanitizers. For a dangling pointer (free(p) and then printf("%d\n", *p)) the report begins like this (addresses shortened and trimmed):

TEXT
==13517==ERROR: AddressSanitizer: heap-use-after-free on address 0x7692e71e0010
READ of size 4 at 0x7692e71e0010 thread T0
    #0 0x557f4ef66252 in main w.c:7
freed by thread T0 here:
    #1 0x557f4ef6621b in main w.c:6
previously allocated by thread T0 here:
    #1 0x557f4ef661ca in main w.c:4
SUMMARY: AddressSanitizer: heap-use-after-free w.c:7 in main

It names the exact line of the bad read, the line of the free and the line of the malloc. A null pointer, by contrast, is the easy case:

TEXT
==13538==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000000
==13538==The signal is caused by a WRITE memory access.
==13538==Hint: address points to the zero page.
    #0 0x638c53b9b1d4 in main n.c:4

A wild pointer produces whatever its leftover bits happen to be, which is why it is the worst of the three: a crash on one run, silent damage to another variable on the next. Memory Errors shows the tools in more detail.

Pointer types and sizes

Every object pointer on a typical desktop system is the same size, 8 bytes on 64-bit and 4 bytes on 32-bit systems, regardless of what it points to:

C Pointer sizes and types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

sizeof p is the size of the address; sizeof *p is the size of what it points to. That second form is the basis of the sizeof *p idiom you'll use with malloc (p = malloc(n * sizeof *p)), which stays correct even if you later change p's type. Note that sizeof *p doesn't actually read memory, so it's fine even when p is null.

The C standard doesn't strictly require all pointer types to have the same size or representation (some old and unusual machines differed), and function pointers are a separate family entirely. That's one reason %p officially requires a void * argument: cast other object pointers to (void *) when printing them.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. After int x = 4; int *p = &x; *p = 9;, what is the value of x?

    p holds x's address, so *p is x itself. Assigning 9 to *p changes x to 9.
  2. 2. What does int *a, b; declare?

    The star applies to each declarator separately, so only a is a pointer. Write int *a, *b; or, better, one declaration per line.
  3. 3. Given int x = 1, y = 2; int *p = &x;, which statement makes p point to y without changing x?

    p = &y; stores a new address in p. *p = y; would copy 2 into x, and the other two don't compile.
  4. 4. Which statement about null pointers is true?

    A null pointer can be tested and compared, never followed. nullptr can only convert to pointer types (or bool), and a null pointer is false in a condition.
  5. 5. On a 64-bit system, double *pd = &d;. What are sizeof pd and sizeof *pd?

    The pointer itself is a 64-bit address (8 bytes), and the double it points to is also 8 bytes. With an int *, the answers would be 8 and 4.

Summary

  • Every object has an address; &x gives it, and printf("%p", (void *)&x) prints it. Addresses change between runs because of ASLR.
  • A pointer stores an address. int *p = &x; declares a pointer to int and points it at x. The star binds to each variable: int *a, b; makes only a a pointer.
  • *p dereferences the pointer: it is the object, so you can read and assign through it. p = &y changes the pointer; *p = 5 changes the pointee.
  • Functions change caller variables through pointers, which is why scanf needs &.
  • The null pointer (NULL, 0, or C23 nullptr) points at nothing. Test it with if (p) or p != NULL and never dereference it.
  • Initialize every pointer; uninitialized and dangling pointers look valid but cause undefined behavior.
  • sizeof p is the pointer's size (8 bytes on 64-bit systems); sizeof *p is the pointee's size.

Next: Pointer Arithmetic