Arrays vs pointers
They behave alike in almost every expression — and then sizeof tells the truth.
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
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.
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.
#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;}