OneBite.Dev - Coding blog in a bite size

Find The Length Of An Array In C++

Code snippet for how to Find The Length Of An Array In C++ with sample and detail explanation

In this article, we will be discussing how to find the length of an array in C++. By understanding this concept, you can effectively manage the data stored in your arrays.

Code Snippet: Find the Length of an Array

First, let’s start with a basic code snippet that can determine the length of an array in C++.

#include <iostream>
using namespace std;

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

Running the above code will output:

The length of the array is: 6

Code Explanation: Find the Length of an Array

Let’s break down the steps on how this code finds the length of an array.

  1. Declare an Array: int myArray[] = {1, 2, 3, 4, 5, 6}; Here we have declared and initialized an integer array named ‘myArray’ with 6 elements.

  2. Find the Size of the Array: int arrayLength = sizeof(myArray)/sizeof(myArray[0]); The built-in function sizeof() in C++ returns the size of a variable, or data type. In this case, sizeof(myArray) will return the total size in bytes of the array. sizeof(myArray[0]) will return the size of one element of the array.

  3. Calculate the length: Dividing the total size of the array by the size of a single element gives us the length (number of elements) of the array. As all elements are of the same type, they’ll have the same size.

  4. Print the length: cout << "The length of the array is: " << arrayLength << endl; Finally, we display the calculated length of the array using C++‘s standard output stream cout.

Remember that the sizeof operator gives the size in bytes, not the length of the array. But as long as we’re dealing with the same type of elements within an array, dividing the total size by the size of one element will indeed give us the length or the number of elements in the array.

c-plus-plus