c / intermediate
Snippet
Pointer Arithmetic with Arrays
In C, array names decay into pointers. Adding an integer to a pointer (pointer arithmetic) moves the pointer by that many elements, not bytes.
snippet.c
1
2
3
4
int arr[] = {10, 20, 30};int *ptr = arr;int val = *(ptr + 2);
Breakdown
1
int *ptr = arr;
Assigns the address of the first element of the array to the pointer 'ptr'.
2
ptr + 2
Calculates the address of the element two positions ahead (the third element).
3
*(ptr + 2)
Dereferences the calculated address to get the value stored at that position (30).