Sub topic 6
Arrays and Pointers: Decay and `sizeof`
Prerequisites
Assume you know basic C syntax, functions, operators, and how to compile a small C program. You should also know that an address identifies a location in memory and that a pointer stores an address.
An array is not a pointer
An array stores a fixed number of adjacent elements. A pointer stores an address. They often work together, but they have different types and behavior.
int a[4] = {10, 20, 30, 40};
int *p = a;The expression a usually changes, or decays, into a pointer to its first element. Therefore, p receives the address of a[0]. These expressions access the same value:
a[2]
*(a + 2)
p[2]
*(p + 2)The array itself still has type int[4]. Only the expression a is converted in contexts where a pointer is needed.
When array decay does not happen
Two important exceptions are sizeof and the address-of operator &.
int a[4];
sizeof a // size of the complete array
sizeof(a[0]) // size of one int
&a // pointer to the whole array
a // usually pointer to a[0]The type of &a is int (*)[4], meaning “pointer to an array of four integers.” It is different from int *.
| Expression | Meaning |
|---|---|
| `a` | Pointer to the first element in most expressions |
| `&a[0]` | Pointer to the first element |
| `&a` | Pointer to the complete array |
| `sizeof a` | Number of bytes occupied by all four elements |
For an array with n elements, the element count is commonly calculated as:
size_t count = sizeof a / sizeof a[0];Array parameters
When an array is used as a function parameter, C adjusts it to a pointer parameter.
#include <stdio.h>
void inspect(int arr[], size_t length) {
printf("pointer-sized: %d\n", sizeof arr == sizeof(int *));
for (size_t i = 0; i < length; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main(void) {
int values[4] = {10, 20, 30, 40};
printf("elements: %zu\n", sizeof values / sizeof values[0]);
inspect(values, sizeof values / sizeof values[0]);
return 0;
}Inside inspect, arr is an int *, so sizeof arr gives the size of a pointer, not the size of the original array. The function needs a separate length argument.
Common errors
- Using
sizeof(arr)inside a function to find the caller's array length. - Assuming
&aandahave the same pointer type. - Passing an array without its length.
- Dereferencing a pointer after the array ends.
- Treating a pointer as if it owns storage for an array.
Exercise
What does sizeof values / sizeof values[0] produce for int values[7];, and what does the same expression usually produce for a parameter declared int values[]?
Show answer
It produces 7 for the actual array. In a function parameter, values is adjusted to int *, so the expression does not compute the original array length.