For the complete documentation index, see llms.txt. This page is also available as Markdown.

🐳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 array

Visually, 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) int occupies 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,

Operation
Result

*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

😎 Cool Fun Fact

We've learnt that we can access arr[0] via *(arr + 0). Since addition is commutative, *(arr + 0) == *(0 + arr), hence 0[arr] works too!

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:

πŸ˜• Why the warning for char* str2 but not char str[] ?

"hello" is a string literal stored in read-only memory.

char[] has no issues since it copies the string literal onto its own array on the stack.

char * is pointing to the same string literal in read-only memory. Writing to it causes undefined behaviour hence the warning.

In fact, if you try compiling the program with stricter flags: clang++ -std=c++17 -Wall -Wextra -pedantic-errors main.cpp -o hello-world, the compiler rejects the code entirely.

To squash this, we can use const char * to assert that we are not going to modify the string.

Last updated

Was this helpful?