CARVIEW |
- Log in to:
- Community
- DigitalOcean
- Sign up for:
- Community
- DigitalOcean

By Sneh and Anish Singh Walia

Introduction
In this article, we are going to learn various ways through which we can find array length in C++. The length of an array refers to the total number of elements present in the corresponding array. For example, take a look at the array below:
int array1[] = { 0, 1, 2, 3, 4 }
The size or length of the array here is equal to the total number of elements in it - which is 5.
Ways to find Length of an Array in C++
There are a few methods through which we can determine the length of an array in C++ language. They are:
- Counting each element
begin()
andend()
functionssizeof()
functionsize()
function in STL- Using Pointers
Now, let us discuss each method one by one with examples and in detail.
1. Counting Each Element
Traversing throughout the given array and simultaneously counting the total number of elements we traversed can give us the array’s length. But if we do not know the array’s length, we cannot use a for loop to traverse the array since a for loop needs a terminating number. This issue can be solved by using a simple for-each loop. Let’s take a look at the code below.
#include<iostream>
#include<array>
using namespace std;
int main()
{
int c;
int arr[]={1,2,3,4,5,6,7,8,9,0};
cout<<"The array is: ";
for(auto i: arr)
{
cout<<i<<" ";
c++;
}
cout<<"\nThe length of the given Array is: "<<c;
return 0;
}
If we run this code, w ewill get the following output:
OutputThe array is: 1 2 3 4 5 6 7 8 9 0
The length of the given Array is: 10
In this code, we traverse the array arr
using a for-each loop with i as the iterator. As the loop traverses, c is incremented. When the loop terminates, the c variable contains the number of times the loop was executed, giving the total length of the array.
2. Using begin() and end()
We can also calculate the length of an array using the standard library’s begin()
and end()
functions. The two functions return iterators pointing to the corresponding array’s start and the end, respectively. Take a look at the given code:
#include<iostream>
#include<array>
using namespace std;
int main()
{
//Given Array
int arr[] = { 11, 22, 33, 44 };
cout<<"The Length of the Array is : "<<end(arr)-begin(arr); //length
return 0;
}
The output of this code will be:
OutputThe Length of the Array is : 4
Here, we can see the difference between the return values of the two functions end()
and begin()
gives us the size or length of the given array arr
. In this case, the difference is 4, which is the length of arr
.
3. Using sizeof() Function to Find Array Length in C++
The sizeof()
operator in C++ returns the size of the passed variable or data in bytes, plus the total number of bytes required to store an array. So, if we divide the size of the array by the size acquired by each element of the same, we can get the total number of elements present in the array.
Let us take a look at how it works.
#include<iostream>
#include<array>
using namespace std;
int main()
{ //Given array
int arr[] = {10 ,20 ,30};
int al = sizeof(arr)/sizeof(arr[0]); //length calculation
cout << "The length of the array is: " <<al;
return 0;
}
The output of this code will be:
OutputThe length of the array is: 3
As we can see, we get our desired length as output.
Limitations of sizeof()
with pointers
When using sizeof()
to find the length of an array, it’s essential to understand its limitations, particularly when dealing with pointers. The sizeof()
operator returns the size of the variable or expression in bytes. However, when applied to a pointer, it returns the size of the pointer itself, not the size of the array it points to.
For example, consider the following code:
int arr[] = {1, 2, 3, 4, 5};
int* ptr = arr;
int size = sizeof(ptr) / sizeof(ptr[0]); // This will not give the correct size
cout << "Size of the array: " << size << endl;
In this case, sizeof(ptr)
will return the size of the pointer ptr
, which is typically 4 or 8 bytes depending on the system architecture. Dividing this by sizeof(ptr[0])
will not give the correct size of the array.
To correctly find the size of an array using sizeof()
, you must use it directly on the array, not on a pointer to the array. Here’s the correct way to do it:
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
cout << "Size of the array: " << size << endl;
This will correctly output the size of the array, which is 5 in this case.
It’s crucial to understand this limitation to avoid incorrect results when working with arrays and pointers in C++.
4. Using the size() Function in STL
There is a size()
function defined in the standard library that returns the number of elements in the given container(array in our case). We can use this function to return the length in the following way:
#include<iostream>
#include<array>
using namespace std;
int main()
{ //Given array
array<int,5> arr{ 1, 2, 3, 4, 5 };
//Using the size() function from STL
cout<<"\nThe length of the given Array is: "<<arr.size();
return 0;
}
On execution, the above code will return the following output:
OutputThe length of the given Array is: 5
5. Using Pointers to Find Array Length in C++
We can also find the length of a given array using pointers. A pointer is a variable that stores the memory address of the object instead of storing the object itself. Let us see how we can use a pointer to get the length of an array.
#include<iostream>
#include<array>
using namespace std;
int main()
{ //Given array
int arr[6] = {5,4,3,2,1,0};
int len = *(&arr + 1) - arr;
//*(&arr + 1) is the address of the next memory location
// just after the last element of the array
cout << "The length of the array is: " << len;
return 0;
}
The output of this code will be:
OutputThe length of the array is: 6
The expression *(arr+1)
gives us the address of the memory space just after the array’s last element. Hence, the difference between it and the array’s starting location or the base address (arr
) gives us the total number of elements in the given array.
Differences between Static and Dynamic Arrays
Static Arrays
Static arrays are arrays whose size is fixed at compile time. This means that the size of a static array must be known at compile time and cannot be changed during runtime. Static arrays are declared using the square brackets []
and their size is specified within the brackets.
Here’s an example of a static array in C++:
int staticArray[5]; // This is a static array of size 5
Dynamic Arrays
Dynamic arrays, on the other hand, are arrays whose size can be changed during runtime. In C++, dynamic arrays are created using the new
keyword and are stored in the heap memory. The size of a dynamic array can be changed using the delete
and new
operators.
Here’s an example of a dynamic array in C++:
int* dynamicArray = new int[5]; // This is a dynamic array of size 5
Using of STL containers (e.g., std::array, std::vector)
STL (Standard Template Library) containers, such as std::array
and std::vector
, provide a more flexible and efficient way to work with arrays in C++. These containers are part of the C++ Standard Library and provide a wide range of operations and functionalities for working with arrays.
Here’s an example of using std::array
in C++:
#include <array>
#include <iostream>
int main() {
std::array<int, 5> arr = {1, 2, 3, 4, 5};
std::cout << "The length of the array is: " << arr.size() << std::endl;
return 0;
}
And here’s an example of using std::vector
in C++:
#include <vector>
#include <iostream>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
std::cout << "The length of the vector is: " << vec.size() << std::endl;
return 0;
}
In both cases, the size()
function is used to get the length of the array or vector.
FAQs
1. How do you find the length of a static array in C++?
To find the length of a static array in C++, you can use the sizeof
operator. The sizeof
operator returns the total number of bytes occupied by the array. To get the number of elements in the array, you need to divide the total number of bytes by the size of each element. Here’s an example:
int staticArray[5];
int length = sizeof(staticArray) / sizeof(staticArray[0]);
2. Why doesn’t sizeof() work with dynamic arrays?
The sizeof
operator does not work with dynamic arrays because it returns the size of the pointer, not the size of the array. Dynamic arrays are allocated on the heap, and the sizeof
operator only returns the size of the pointer that points to the first element of the array, not the size of the array itself.
3. What is the difference between array length and array size?
Array length and array size are often used interchangeably, but they have a subtle difference. Array length refers to the number of elements in the array, while array size refers to the total number of bytes occupied by the array. For example, if you have an array of integers, the length of the array is the number of integers it can hold, while the size of the array is the total number of bytes required to store those integers.
4. How can I find the size of a vector or std::array?
To find the size of a std::vector
or std::array
, you can use the size()
method. This method returns the number of elements in the container. Here’s an example for std::vector
:
std::vector<int> vec = {1, 2, 3, 4, 5};
int size = vec.size();
And here’s an example for std::array
:
std::array<int, 5> arr = {1, 2, 3, 4, 5};
int size = arr.size();
5. Can you get the length of an array passed to a function?
When an array is passed to a function, it decays into a pointer to the first element of the array. This means that the function does not receive the array itself, but a pointer to its first element. As a result, you cannot directly get the length of the array within the function using the sizeof
operator. However, you can pass the length of the array as a separate parameter to the function.
Here’s an example to demonstrate how an array decays into a pointer when passed to a function, making it impossible to directly get the length of the array using the sizeof
operator within the function. However, we can pass the length of the array as a separate parameter to the function.
#include <iostream>
void printArray(int arr[], int length) {
for(int i = 0; i < length; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
}
int main() {
int staticArray[5] = {1, 2, 3, 4, 5};
int length = sizeof(staticArray) / sizeof(staticArray[0]);
printArray(staticArray, length);
return 0;
}
Conclusion
In this tutorial, we explored the different approaches to determine the length of an array in C++. While each method has its own way of returning the length, we recommend utilizing the for-each loop due to its enhanced code readability and cross-platform compatibility. This approach simplifies the process of iterating through arrays, making it easier to understand and maintain your code.
To further expand your knowledge on working with arrays in C++, we encourage you to explore the following tutorials:
- String Array in C++: Learn how to work with arrays of strings in C++ and understand the nuances of string manipulation.
- Return Array in C++ Function: Discover how to return arrays from functions in C++ and the best practices to follow.
- Two-Dimensional Array in C++: Explore the concept of two-dimensional arrays in C++ and how to effectively use them in your programs.
- Convert String to Char Array in C++: Understand the process of converting strings to character arrays in C++ and the applications of this conversion.
By following these tutorials, you will gain a deeper understanding of array manipulation in C++ and be able to tackle more complex tasks with confidence.
References
- How do I find the length of an array? - Stack Overflow question,
- for-each loop in C++ - JournalDev post.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
About the author(s)

Helping Businesses stand out with AI, SEO, & Technical content that drives Impact & Growth | Senior Technical Writer @ DigitalOcean | 2x Medium Top Writers | 2 Million+ monthly views & 34K Subscribers | Ex Cloud Engineer @ AMEX | Ex SRE(DevOps) @ NUTANIX
Still looking for an answer?
- Table of contents
- Ways to find Length of an Array in C++
- Differences between Static and Dynamic Arrays
- Using of STL containers (e.g., std::array, std::vector)
- FAQs
- Conclusion
- References
Deploy on DigitalOcean
Click below to sign up for DigitalOcean's virtual machines, Databases, and AIML products.
Become a contributor for community
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
DigitalOcean Documentation
Full documentation for every DigitalOcean product.
Resources for startups and SMBs
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Get our newsletter
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
The developer cloud
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Get started for free
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.