← 👉 Pointers & Arrays
Subtopic 3 of 5

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

  1. In an expression, a becomes &a[0].
  2. sizeof(a) = number of elements × element size.
  3. &a is a pointer to the whole array, so &a + 1 jumps past the whole array.
  4. 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.

type of the expressionunsigned long
value16
Memory (one box per element, address below)
1
a[0]
@100
2
a[1]
@101
3
a[2]
@102
4
a[3]
@103
100
p
@104
104
s[0]
@105
105
s[1]
@106
0
s[2]
@107

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).

step 1 of 6
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)
main()
no variables yet
Output

Check yourself

int a[10]; and a function void f(int a[]). Inside f, sizeof(a) on a 64-bit machine is

Remember: a decays to &a[0]; sizeof(a) is the whole array; a parameter array is a pointer.
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.