π³Arrays & Strings
Thus far, pointers pointed to a singular variable. But what if we have multiple values stored together (exactly, like an array!)
Arrays
To declare an array:
int arr[3] = {10, 20, 30}; // array
int* p_arr = arr; // pointer to arrayVisually, this is how an array is represented:

Note that:
All 3 elements sit side-by-side (i.e there exists no gaps between them). This is what we mean by contiguous memory.
You may also have noticed that the difference between each memory address is 4 bytes. This because (usually)
intoccupies 4 bytes.
Pointer Arithmetic
Since p_arr stores the address of the first element, you can access arr[0] via dereferencing *p_arr.
What about arr[1]? The cool thing about pointer arithmetic is that it's type-aware, you can simply perform (p_arr + 1) to move forward by 1 element of type int (i.e 4 bytes).
Functionally,
*p_arr
Move p_arr by 0 bytes, dereference to get arr[0]
*(p_arr + 1)
Move p_arr by 4 bytes, dereference to get arr[1]
*(p_arr + 2)
Move p_arr by 8 bytes, dereference to get arr[2]
Note that arr also decays into a pointer to the first element that shares the same memory address as p_arr, hence operations that can be done with arr can also be done with p_arr
Strings
Fundamentally, a string is simply an array of characters ending with a special character \0 (i.e null terminator)
The usual pointer arithmetic rules that we've learnt above apply too.
Notice when we compile, we get a warning:

Last updated
Was this helpful?
