OneBite.Dev - Coding blog in a bite size

Count Array's Length In C++

Code snippet for how to Count Array's Length In C++ with sample and detail explanation

Understanding how to count the length of an array in C++ is a crucial skill for any developer working with this language. It is used frequently, as it assists in operations such as loops, and function calls where knowing the size of the array is essential.

Code snippet for Counting an Array’s Length

To get the length of an array, you can divide the size of the entire array by the size of an element of the array. Here is a simple C++ code snippet that demonstrates this:

#include<iostream>
using namespace std;

int main() {
    int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    int arraySize = sizeof(arr) / sizeof(arr[0]); 
    cout << "The size of the array is: "<< arraySize; 
    return 0;
}

Code Explanation for Counting an Array’s Length

In the code snippet above, we start by including the iostream standard library to allow for input and output operations, such as cout.

Next, we declare an integer array named arr and initialize it with 9 numbers.

The real magic happens in the next line where we compute the size of the array. We use the sizeof() function for this operation.

int arraySize = sizeof(arr) / sizeof(arr[0]); 

The sizeof(arr) function returns the total size (in bytes) of the entire array. The sizeof(arr[0]) function returns the size (in bytes) of one element of the array. By dividing the total size by the size of one element, we get the total number of elements in the array.

We then print out the size of the array using cout.

The output of the program will be: The size of the array is: 9. This confirms that our code works, as our initially declared array contains 9 elements.

However, it’s important to note that this way of counting the array’s length only works if the array is defined in the same scope as where you are trying to count the length. If the array is passed to a function, the array decays to a pointer and the method will not work. In such situations, the array size needs to be passed along with the array.

c-plus-plus