3.3Arrays, decay and sizeof
The idea
An array name usually decays to a pointer to its first element, but it is not a pointer: sizeof and & still see the whole array.
Think of it like this: An array is a whole shelf; its name on a label usually means "the first slot", but weighing the shelf (sizeof) weighs everything.
Why it exists
sizeof-of-array versus sizeof-of-pointer is a recurring GATE trap, especially for function parameters.
How it works
- In an expression, a becomes &a[0].
- sizeof(a) = number of elements × element size.
- &a is a pointer to the whole array, so &a + 1 jumps past the whole array.
- A parameter written int a[] is really int *a; inside the function sizeof(a) is the size of a pointer.
Worked example: int a[4]; int *p = a;
sizeof(a) = 16 (4 × 4 bytes), sizeof(p) = 8. a + 1 is the address of a[1], but &a + 1 is 16 bytes further on.
Now play with it
- →Run the lab on sizeof(a), sizeof(p), a + 1 and &a + 1.
- →In the program tab see 16 in main but 8 inside f.
sizeof and the array name. a is an array of 4 ints; p is a pointer to the same memory.
Memory (one box per element, address below)
Gold = the object the expression names. Blue = the element a pointer result points to. Each box stands for one element; real addresses grow by sizeof(element).
Inside f the array has decayed to a pointer, so sizeof gives the size of a pointer (8), not of the array (16).
1#include <stdio.h>2void f(int a[]) {3 printf("inside f: %d\n", (int)sizeof(a));4}5int main() {6 int v[4] = {1, 2, 3, 4};7 printf("in main: %d\n", (int)sizeof(v));8 f(v);9 return 0;10}
The gold line is the statement about to run.
Call stack (top first)
Output
Check yourself
int a[10]; and a function void f(int a[]). Inside f, sizeof(a) on a 64-bit machine is
Exam notes (the dense version)
In most expressions an array name decays to a pointer to its first element, so a, &a[0] and a + 0 are the same address. Exceptions: sizeof a gives the whole array size, and &a is a pointer to the whole array (so &a + 1 jumps past it). An array parameter is really a pointer, so inside the function sizeof gives 8, not the array size. Arrays cannot be assigned.
Previous year questions: Pointers & Arrays (11)
PYQs are grouped by topic, so this is the full set for Pointers & Arrays; try the ones that match this subtopic. Open all 11 on the topic page.