c / intermediate
Snippet
Array Decay and Pointer Arithmetic
In C, arrays 'decay' into pointers to their first element when passed to functions. This means the size information is lost inside the function. Use pointer arithmetic (ptr + offset) to navigate the memory layout manually.
snippet.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>void inspect_array(int *ptr, int size) {printf("Value at index 2: %d\n", *(ptr + 2));printf("Size of pointer: %zu bytes\n", sizeof(ptr));}int main(void) {int data[] = {10, 20, 30, 40, 50};printf("Size of actual array: %zu bytes\n", sizeof(data));// Array 'data' decays to a pointer to its first elementinspect_array(data, 5);return 0;}
Breakdown
1
*(ptr + 2)
Accesses the third element by adding an offset to the base pointer.
2
sizeof(data)
Returns the total size of the array in bytes because it is still in scope.