Accessing elements by index
What you'll learn: How to use pointer arithmetic and the subscript operator to read or modify data stored in a dynamic array.
The Post Office Analogy
Imagine a row of identical P.O. boxes. In a static array, the post office owns the boxes, and you just rent them. In a dynamic array, you own the entire row because you bought the land (memory) yourself using malloc.
Even though you are managing the memory manually, the way you look inside the boxes remains the same. Because a dynamic array is just a contiguous block of memory, your computer knows exactly where the "third box" is by starting at the first box and jumping over two spaces.
Using the Subscript Operator
The most common way to access an element in a dynamic array is the exact same way you do it with a normal array: using square brackets [].
Even though your array is technically a pointer, C treats array[i] as shorthand for "start at the pointer address and move i steps forward."
#include <stdio.h>
#include <stdlib.h>
int main() {
// 1. Allocate memory for 3 integers
int *scores = malloc(3 * sizeof(int));
// 2. Check if allocation succeeded
if (scores == NULL) return 1;
// 3. Accessing by index to write data
scores[0] = 95;
scores[1] = 88;
scores[2] = 72;
// 4. Accessing by index to read data
printf("The second score is: %d\n", scores[1]);
// 5. Always free your memory!
free(scores);
return 0;
}
Why this works
Under the hood, when you write scores[1], C performs pointer arithmetic. It takes the memory address stored in scores, adds the size of one integer to it, and looks at that specific spot in RAM.
This is why accessing elements is incredibly fast (O(1) time complexity). It doesn't matter if your dynamic array has 10 elements or 10 million; the computer can calculate the exact location of any index instantly without having to scan through the elements before it.
Safety Warning
Unlike some modern languages, C will not stop you if you try to access scores[500] on an array that only has 3 slots. This is called an "out-of-bounds" error. It might crash your program or, worse, return "garbage" data from a random part of your computer's memory. Always keep track of your array's size in a separate variable.
Key takeaway
Access dynamic array elements using the array[index] syntax just like static arrays, as the compiler automatically calculates the memory offset for you.