Accessing elements

for Zig 0.15.2 Buy

Accessing elements

When we declare an array:

 const a_numbers = [_]u8{ 5, 4, 3, 21, 13 };

a_numbers points to a structure with 5 positions like this:

5

4

3

21

13

indexes:

0

1

2

3

4

To access the different elements of an array, we use indexes starting from 0. This is because an index actually represents an offset of i positions from the beginning of the array.

Here are some formulas to help clarify these concepts:

Element number = index + 1

Index = element number - 1

Final index = array length - 1

If you're wondering how much memory a 5 element array of type u8 takes:

5 elements * 8 bits = 40 bits

You probably remember that 8 bits make 1 byte, so we can also say that a u8 array of length 5 takes up 5 bytes.

To access an element in the array, we use the index to “point” to the desired position. Let’s see how to access the first and last positions:

array_position.zig

const std = @import("std");

const print = std.debug.print;

pub fn main() void {

   const a_numbers = [_]u8{ 8, 5, 10, 6, 12 };

    const n_first_position = 0;

    const n_last_position = a_numbers.len;

    print("The first element of a_numbers is at index [{}]: {}\n", 

     .{ n_first_position, a_numbers[n_first_position] });

    print("The last element is at index [{}]: {}\n", 

     .{ n_last_position, a_numbers[n_last_position] });

}

$ zig run array_position.zig

array_position.zig:11:98: error: index 5 outside array of length 5

Can you spot the mistake?

The mistake we made is a common one. We confused the length with the last position. Since indexes start at 0, the last position is at array length - 1, as we mentioned earlier. By writing:

    const n_last_position = a_numbers.len - 1;

… the problem is solved and Zig runs the program correctly:

$ zig run array_position.zig

The first element of a_numbers is at index [0]: 8  

The last element is at index [4]: 12

Arrays
Mutable arrays
© 2025 - 2026 Zen of Zig