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

Calculating array size with `sizeof`

Calculating array size with sizeof

What you'll learn: How to use the sizeof operator to automatically determine the number of elements in an array.

In C, an array doesn’t "know" how many items it contains. If you create an array of 10 integers, the computer simply sets aside a block of memory and forgets the count. This becomes a problem when you want to loop through every item; you have to remember the size yourself, or your code might accidentally wander into memory it doesn't own.

The sizeof operator

The sizeof operator is a built-in tool that tells you how many bytes of memory a piece of data occupies. Think of it like a kitchen scale: it tells you the total weight of a bag of apples, but it doesn't tell you how many apples are inside.

If you use sizeof on an array, it returns the total bytes used by the entire array. For example, if an integer (int) takes up 4 bytes and you have an array of 5 integers, sizeof will return 20.

The "Total / One" Trick

To find out how many elements are in the array (the number of apples), we use a bit of simple math. We take the weight of the whole bag and divide it by the weight of one apple.

In C terms: we divide the total size of the array by the size of its first element.

#include <stdio.h>

int main() {
    // An array of integers
    int numbers[] = {10, 20, 30, 40, 50, 60, 70};

    // 1. Get total size of the array in bytes
    size_t totalSize = sizeof(numbers); 

    // 2. Get size of a single element (the first one)
    size_t oneSize = sizeof(numbers[0]);

    // 3. Divide total by one to get the count
    int length = totalSize / oneSize;

    printf("The array takes up %zu bytes.\n", totalSize);
    printf("Each element takes up %zu bytes.\n", oneSize);
    printf("The number of elements is: %d\n", length);

    return 0;
}

Why this is useful

Hard-coding numbers (like using 7 in a loop) is risky. If you add two more numbers to your array later, you have to find every place you wrote 7 and change it to 9. By using the sizeof(array) / sizeof(array[0]) formula, your code stays flexible. If the array grows or shrinks, the math updates itself automatically.

Key takeaway

To find the number of elements in an array, divide the total size of the array by the size of its first element: sizeof(arr) / sizeof(arr[0]).