Course contentsShow
← C
Lesson 238 of 1,2193. Operators and ExpressionsFree lesson

The Indirection operator `*`

The Indirection operator *

What you'll learn: How to use the asterisk symbol to "go to" a memory address and access the actual value stored there.

The "Treasure Map" Analogy

In C, a pointer is like a treasure map. The pointer itself isn't the gold; it’s just a piece of paper with an address written on it (like "123 Oak Street"). If you look at the pointer, you just see the address.

But what if you want the gold? You have to follow the map to the destination. In programming, this act of "following the map" to see what’s inside the house is called dereferencing, and we use the indirection operator (*) to do it.

How it Works

When you place the * symbol in front of a pointer variable, you are telling the computer: "Don't give me the address; give me the value stored at that address."

Imagine you have a box called goal containing the number 100. You also have a pointer called ptr that holds the address of that box.

  • Printing ptr shows you a messy memory address (like 0x7ff...).
  • Printing *ptr shows you 100.

The * operator literally "indirects" your request. Instead of stopping at the pointer, the CPU bounces off the pointer and grabs the data from the location it points to.

Seeing it in Code

The asterisk can be confusing because it is used to declare a pointer, but when used in an expression, it acts as the indirection operator.

#include <stdio.h>

int main() {
    int cookies = 12;      // A regular variable
    int *ptr = &cookies;   // 'ptr' now holds the address of 'cookies'

    // Using the indirection operator to see the value
    printf("Address stored in ptr: %p\n", (void*)ptr);
    printf("Value at that address: %d\n", *ptr); 

    // We can even change the value remotely!
    *ptr = 25; 
    
    printf("New value of cookies: %d\n", cookies);

    return 0;
}

In the example above, *ptr = 25 doesn't change the address stored in the pointer; it reaches through the pointer and changes the cookies variable to 25.

Key takeaway

The indirection operator * acts like a "teleport" button that takes you from a memory address to the actual data stored at that spot.