Pointers and Arrays
Prerequisites: Pointers: introduction
An array's name, used on its own, decays into a pointer to its first element — which is why array indexing and pointer arithmetic are two views of the exact same thing:
int nums[3] = {10, 20, 30};
int *p = nums; // same as &nums[0]
printf("%d\n", nums[1]); // 20
printf("%d\n", *(p + 1)); // 20 — identical to nums[1]
This is also why an array parameter is really just a pointer in
disguise, and sizeof behaves differently on it than on the
original array:
void printSize(int arr[]) {
printf("%zu\n", sizeof(arr)); // size of a POINTER, e.g. 8 — NOT the array!
}
int main(void) {
int nums[5] = {1, 2, 3, 4, 5};
printf("%zu\n", sizeof(nums)); // 20 — 5 ints, the real array size
printSize(nums);
return 0;
}
Common mistakes
- Using
sizeof(arr) / sizeof(arr[0])inside a function that received the array as a parameter — it silently computes the wrong number, sincearrthere is just a pointer. Pass the length as a separate parameter instead.