Example 1 — Array versus pointer
Indexing works on both, but sizeof tells them apart.
#include <stdio.h>
int main(void) {
int arr[5] = {1, 2, 3, 4, 5};
int *p = arr;
printf("arr[2] = %d, p[2] = %d, *(p+2) = %d\n", arr[2], p[2], *(p + 2));
printf("sizeof arr = %zu\n", sizeof arr);
printf("sizeof p = %zu\n", sizeof p);
int sum = 0;
for (int *q = arr; q < arr + 5; q++) sum += *q;
printf("sum = %d\n", sum);
return 0;
} How It Works
- Three spellings reach the same element.
sizeof arris 5 ints;sizeof pis one pointer (8 bytes on 64-bit).- A pointer loop walks from
arrtoarr + 5.
