How to Get the Size of an Array in C++

This tutorial will guide you through different methods of obtaining the length of an array in C++.

How to Get the Size of an Array in C++

An array is a fundamental data structure in C++ that allows you to store multiple values of the same type in a contiguous block of memory. Sometimes, you may need to find the length (or size) of an array.

Before we begin, it's important to note that C++ arrays do not store their size within the array structure, unlike some other high-level data structures or languages. Therefore, the size of the array has to be managed separately by the programmer or inferred from the context in which the array is used.

Let's start with the most common and direct method of obtaining the length of an array.

Method 1: Using the sizeof Operator

The sizeof operator in C++ returns the size in bytes of the object or type. We can use this operator to calculate the length of an array. Here's how:

#include <iostream>

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int length = sizeof(arr) / sizeof(arr[0]);
    std::cout << "The length of the array is: " << length << std::endl;
    return 0;
}

In this example, sizeof(arr) gives us the total size in bytes of the array, and sizeof(arr[0]) gives us the size in bytes of a single element. Dividing the total size by the size of a single element gives us the length of the array.

Compile the program:

g++ size.cpp

You can then run the resulting output as shown:

The length of the array is: 5

Method 2: Using std::size from C++17

If you're using C++17 or later, you can use the std::size function from the standard library to get the length of an array:

#include <iostream>
#include <iterator>

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int length = std::size(arr);
    std::cout << "The length of the array is: " << length << std::endl;
    return 0;
}

The std::size function returns the number of elements in a container, which, in this case, is our array.

Method 3: Using std::end and std::begin

Another method to find the length of an array is by subtracting the beginning pointer of the array from the end pointer. The std::begin and std::end functions return pointers to the beginning and end of the array, respectively.

#include <iostream>
#include <iterator>

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int length = std::end(arr) - std::begin(arr);
    std::cout << "The length of the array is: " << length << std::endl;
    return 0;
}

Method 4: Using Templates

If you want to use a function that calculates the length of any array, you can use a function template. Here is an example:

cppCopy code#include <iostream>

template <typename T, std::size_t N>
constexpr std::size_t array_length(T (&)[N]) {
    return N;
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    std::cout << "The length of the array is: " << array_length(arr) << std::endl;
    return 0;
}

This template function receives a reference to an array of any type and size. The std::size_t N in the template parameters allows the compiler to deduce the size of the array automatically. The constexpr keyword ensures that the function can be evaluated at compile time, making it suitable for use in contexts where a constant expression is required.

Caveats and Considerations

While the methods described above work for arrays whose size is known at compile time, they will not work as expected for pointers or for arrays passed to functions. This is because when arrays are passed to functions, they decay to pointers, losing information about their size.

For example, consider the following code:

cppCopy code#include <iostream>

void printLength(int arr[]) {
    int length = sizeof(arr) / sizeof(arr[0]);
    std::cout << "The length of the array is: " << length << std::endl;
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    printLength(arr);
    return 0;
}

You might expect this code to print The length of the array is: 5, but instead it will likely print The length of the array is: 1 or 2 (depending on the architecture), because arr in printLength is actually a pointer, and sizeof(arr) gives the size of the pointer, not the array.

In such cases, one common solution is to pass the size of the array as an additional argument to the function:

cppCopy code#include <iostream>

void printLength(int arr[], int length) {
    std::cout << "The length of the array is: " << length << std::endl;
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    printLength(arr, sizeof(arr) / sizeof(arr[0]));
    return 0;
}

Another approach is to use higher-level data structures like std::array or std::vector that maintain their size, but these come with additional overhead and may not be suitable for all situations.

Conclusion

This tutorial introduced different methods to get the length of an array in C++. The best method to use depends on your specific needs and constraints, and whether you're dealing with arrays whose size is known at compile time or with arrays passed to functions.

Table of Contents
Great! Next, complete checkout for full access to GeekBits.
Welcome back! You've successfully signed in.
You've successfully subscribed to GeekBits.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info has been updated.
Your billing was not updated.