Course contentsShow
← C
Lesson 473 of 1,2197. PointersFree lesson

The equivalence of `a[i]` and `*(a + i)`

The equivalence of a[i] and *(a + i)

What you'll learn: You will discover how C treats array indexing as a shorthand for pointer arithmetic and dereferencing.

In C, arrays and pointers are more like siblings than distant cousins. While we often use square brackets to access array elements, the compiler sees something quite different under the hood. Understanding this relationship is the "aha!" moment for mastering C memory management.

The Secret Shorthand

When you write my_array[3], you are using "array subscript notation." It’s comfortable and easy to read. However, to the C compiler, this is just a user-friendly shorthand for "pointer notation."

The compiler translates a[i] into *(a + i).

Let’s break that down:

  1. a: The name of an array acts as a pointer to its first element (index 0).
  2. + i: This performs pointer arithmetic. It says, "Move forward by i units of memory."
  3. *: The dereference operator says, "Go to that calculated address and grab the value stored there."

The Mailbox Analogy

Imagine a row of identical mailboxes. The name of the street is a.

  • If you want the mail in the 4th box, you might say a[3].
  • The mailman, however, thinks in steps. He starts at the beginning of the street (a), walks exactly 3 houses down (+ 3), and opens the door (*) to get the letter.

Whether you use the label or the steps, you end up at the exact same mailbox.

Seeing it in Code

Because these two forms are identical to the compiler, you can use them interchangeably.

#include <stdio.h>

int main() {
    int prices[3] = {10, 20, 30};

    // Traditional array access
    printf("Index 1: %d\n", prices[1]);

    // Pointer arithmetic access
    // This adds 1 to the base address, then dereferences it
    printf("Pointer 1: %d\n", *(prices + 1));

    return 0;
}

Both printf statements will output 20. In the second version, the compiler automatically calculates the byte offset based on the size of an int, so you don't have to worry about the actual memory addresses.

Key takeaway

In C, a[i] and *(a + i) are functionally identical; the brackets are just "syntactic sugar" to make pointer arithmetic easier to read.