Pointers & Memory · beginner · ~10 min

Pointers and arrays

Understand array-to-pointer decay and the equivalence `a[i] == *(a+i)`.

Lesson

In most contexts, the name of an array decays to a pointer to its first element. So a[i] is exactly the same as *(a + i). That's why functions that take arrays can declare them as either int a[] or int *a.

The exceptions: sizeof(a) on a declared array gives the total size in bytes; passed as a pointer, you'd get the pointer's own size. And &a (address-of array) has a different type from a (pointer to first element).

Common mistakes

  • Computing sizeof(arr) / sizeof(arr[0]) inside a function: arr has decayed to a pointer, so you get a wrong (or even meaningless) value.
  • Treating a 2D array argument as int ** — that's a different type.