Course contentsShow
← C
Lesson 386 of 1,2196. Arrays and StringsFree lesson

Accessing elements with the `[]` operator

Accessing elements with the [] operator

What you'll learn: How to retrieve or change specific values inside an array by using their position number.

Once you have created an array, you can think of it as a row of lockers in a school hallway. Each locker holds a piece of data, but to get to that data, you need to know the locker's number. In C, we use the square bracket operator [] to specify which "locker" we want to open.

The Zero-Based Rule

The most important rule in C arrays is that we start counting from zero. If you have an array of five integers, the first item is at index 0, and the last item is at index 4.

Think of a hotel where the ground floor is labeled Floor 0. If you want the very first room, you go to floor 0. If you want the second room, you go to floor 1. It feels a bit strange at first, but it is a fundamental rule of how C manages memory.

Reading and Writing

You can use the [] operator for two things: looking at what is inside a slot (reading) or putting something new into a slot (writing).

To write a value, you put the array name and the index on the left side of an equals sign. To read a value, you simply use the array name and index anywhere you would normally use a variable.

#include <stdio.h>

int main() {
    int highScores[3];

    // Writing values to specific slots
    highScores[0] = 95;  // The first slot
    highScores[1] = 82;  // The second slot
    highScores[2] = 100; // The third slot

    // Reading values from specific slots
    int firstPlace = highScores[2];
    
    printf("The top score is %d\n", firstPlace);
    printf("The middle score is %d\n", highScores[1]);

    return 0;
}

Staying Within Bounds

When using [], you must be careful not to ask for an index that doesn't exist. If your array has a size of 3, asking for highScores[5] is like trying to open a locker that isn't there. C won't always stop you from doing this, but it will cause your program to crash or behave unpredictably. Always remember: the highest valid index is always Size - 1.

Key takeaway

Use array[index] to access a specific element, remembering that the first element is always at index 0.