Skip to content
Codescope

Arrays vs pointers

They behave alike in almost every expression — and then sizeof tells the truth.

core9 min7 steps

Before you start

In most C code, an array and a pointer act the same way. arr[i] and *(arr + i) compile to the same instructions. This is convenient, and it is also the source of endless confusion.

The difference sneaks in at exactly two moments: when you ask sizeof, and when you pass the array to a function. Miss either, and you get a bug that looks impossible but is actually the language telling you these are two different things.

This lesson shows exactly when arrays behave like pointers, when they don't, and why sizeof(arr) gives one answer here and a different answer three lines later.

Stack

main()sizeof arr = 20 · sizeof p = 8
arr[0]
10
0x1000
arr[1]
20
0x1004
arr[2]
30
0x1008
arr[3]
40
0x100c
arr[4]
50
0x1010
pint *
0x1000
0x1020

Six boxes on screen, but only one of them is the array.

Step 1 of 7. Two different things in memory. `arr` is 20 bytes of storage — five ints, back to back, starting at `0x1000`. `p` is 8 bytes of storage holding the number `0x1000`. The array *is* the data; the pointer merely refers to it.

01 / 07

Step 01 / 07

Two different things in memory

arr is 20 bytes of storage — five ints, back to back, starting at 0x1000.

p is 8 bytes of storage holding the number 0x1000. The array *is* the data; the pointer merely refers to it.

arrays-vs-pointers.cC
#include <stdio.h>void show(int a[], size_t n) {    printf("%zu\n", sizeof a);   /* 8 — a is a pointer */    printf("%d\n", a[0]);}int main(void) {    int  arr[5] = {10, 20, 30, 40, 50};    int *p = arr;    printf("%zu\n", sizeof arr);  /* 20 */    printf("%d %d\n", arr[2], *(arr + 2));    printf("%d\n", 2[arr]);    show(arr, 5);    return 0;}