Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Ways to Find the Length of an Array in C++
2.1.
Counting Each Element
2.2.
C++
2.3.
Using begin() & end() Functions
2.4.
C++
2.5.
sizeof() Function
2.6.
C++
3.
size() Function in STL
3.1.
C++
4.
Using Pointers
4.1.
C++
5.
Frequently Asked Questions 
5.1.
What happens if I use the wrong method to calculate the size of an array?
5.2.
Can I use the size() function on any type of array?
5.3.
Why is it important to know the size of an array?
5.4.
What does size() return in C++?
6.
Conclusion
Last Updated: Oct 3, 2024
Easy

Size of Array in C++

Introduction

In C++, arrays are a fundamental data structure used to store multiple elements of the same data type. When working with arrays, it's essential to know the size or length of the array to perform various operations efficiently. 

Size of Array in C++

In this article, we'll learn different methods to find the size of an array in C++, including counting elements, using begin() & end() functions, the sizeof() function, the size() function in STL, & pointers. 

Ways to Find the Length of an Array in C++

Counting Each Element

One straightforward method to determine the size of an array in C++ is by counting each element. This involves using a loop to iterate through the array & incrementing a counter until the end of the array is reached. This method is particularly useful when the array does not have a predefined size or when using arrays that are not null-terminated.

Here's how you can implement this method:

  • C++

C++

#include <iostream>

using namespace std;

int main() {

   int myArray[] = {5, 10, 15, 20, 25};  // An array of integers

   int count = 0;  // Counter for the array elements

   // Loop to count elements

   for(int i = 0; myArray[i]; i++) {

       count++;

   }

   cout << "Number of elements in the array: " << count << endl;

   return 0;

}
You can also try this code with Online C++ Compiler
Run Code

Output

Number of elements in the array: 9


In this example, the loop continues until it has iterated through each element of the array, increasing the count by one on each iteration. This method is simple but becomes less efficient as the size of the array increases.

Using begin() & end() Functions

Another method to find the size of an array involves using the begin() & end() functions provided by C++. These functions offer a way to obtain iterators pointing to the beginning & end of the array, respectively. The distance between these two iterators represents the size of the array.

Example of using begin() & end():

  • C++

C++

#include <iostream>

#include <iterator>  // For std::begin() & std::end()

using namespace std;

int main() {

   int myArray[] = {5, 10, 15, 20, 25, 30};

   // Calculate the size using std::begin() & std::end()

   int size = distance(begin(myArray), end(myArray));

   cout << "The array has " << size << " elements." << endl;

   return 0;

}
You can also try this code with Online C++ Compiler
Run Code

Output

The array has 6 elements.


This method is not only straightforward but also safe & effective, especially for arrays where the length is not directly known or specified.

sizeof() Function

The sizeof() function in C++ can also be used to find the size of an array. This function returns the total byte size of the array. To find the number of elements, you divide this by the size of one element in the array.

Here’s an example:

  • C++

C++

#include <iostream>

using namespace std;

int main() {

   int myArray[] = {5, 10, 15, 20, 25, 30, 35};

   // Calculate the size using sizeof()

   int size = sizeof(myArray) / sizeof(myArray[0]);

  cout << "The array has " << size << " elements." << endl;

   return 0;

}
You can also try this code with Online C++ Compiler
Run Code

Output

The array has 7 elements.


This approach provides a quick & reliable way to determine the size of the array when the data type of the array elements is known.

size() Function in STL

The size() function provided by the Standard Template Library (STL) in C++ is another efficient way to determine the length of an array, especially when you are working with containers like std::array or std::vector. This function returns the number of elements in the container, which can be particularly useful when dealing with dynamic data structures where the size of the array can change during runtime.

Here’s how you can use the size() function with a std::array:

  • C++

C++

#include <iostream>

#include <array>

using namespace std;

int main() {

   array<int, 5> myArray = {5, 10, 15, 20, 25};

   // Using the size() function to get the number of elements

   cout << "The array has " << myArray.size() << " elements." << endl;

   return 0;

}
You can also try this code with Online C++ Compiler
Run Code

Output

The array has 5 elements.


In this code snippet, myArray is an std::array which has a fixed size of 5. By calling myArray.size(), we can directly obtain the number of elements in the array without needing to calculate it manually or worry about errors like exceeding array bounds.

The size() function is not only simple to use but also provides a clear & direct method for obtaining the size of an array, making your code cleaner & more maintainable. It’s particularly useful in modern C++ programming, where using STL containers can help manage complex data structures more effectively.

Using Pointers

For arrays declared in traditional C++ style, pointers can be used to determine the size of an array. This method involves pointers to navigate through the array's memory address space & count the number of elements until the end is reached.

Here's a simple implementation using pointers:

  • C++

C++

#include <iostream>

using namespace std;

int main() {

   int myArray[] = {10, 20, 30, 40, 50, 60};

   int* begin = myArray; // Pointer to the first element

   int* end = myArray + sizeof(myArray) / sizeof(myArray[0]);  // Pointer to the element beyond the last

   int count = 0;

   for (int* ptr = begin; ptr != end; ptr++) {

       count++;

   }

   cout << "The array has " << count << " elements." << endl;

   return 0;

}
You can also try this code with Online C++ Compiler
Run Code

Output

The array has 6 elements.


This code uses two pointers, begin & end, to traverse the array. The loop iterates from the beginning to the end of the array, incrementing the count for each element. This method provides a more hands-on approach to array size calculation & can be useful in scenarios where standard functions are not available or when learning pointer arithmetic.

Frequently Asked Questions 

What happens if I use the wrong method to calculate the size of an array?

Using the wrong method to determine the size of an array in C++ can lead to errors like out-of-bounds access, which may cause your program to crash or behave unexpectedly. For instance, using sizeof() on a pointer rather than an array will return the size of the pointer itself, not the length of the array it points to. Always ensure you're using the correct method for your specific array type to avoid these common pitfalls.

Can I use the size() function on any type of array?

The size() function is specific to C++ STL containers like std::array and std::vector. It does not work on built-in C++ arrays. For traditional C-style arrays, you should use methods like sizeof() or pointer arithmetic to determine the array size.

Why is it important to know the size of an array?

Knowing the size of an array is crucial for preventing memory leaks & buffer overflow issues in your programs. It helps in managing how much data you can safely store & process in an array. Understanding array size is also essential for loops that iterate over array elements, ensuring that you do not access elements beyond the array's memory, which can lead to undefined behavior and security vulnerabilities in your software.

What does size() return in C++?

In C++, the size() function is used with containers like vectors, strings, and arrays to return the number of elements they contain. It provides a quick way to determine the length of the container.

Conclusion

In this article, we have learned several methods to find the size or length of an array in C++, including counting each element manually, using the begin() & end() functions, the sizeof() function, the size() function provided by the STL array container, & using pointers. Each method has its own advantages & use cases, & learning these techniques help us to  determine the size of arrays in your C++ programs.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.

Live masterclass