This tutorial will discuss multiple ways to get the size of an array in C++.
Table Of Contents
To get the size of an array, we have two options:
Using the C++ std::size function:
In C++17 and later, the std::size() function was introduced to easily obtain the number of elements in an array. You can pass the array as an argument into the std::size() function, and it will return the number of elements in the array or the size of the array.
Here’s how you can use it with an array of integers.
Let’s see the complete example,
#include <iostream> #include <iterator> int main() { // Array of integers with 5 elements int arr[] = {78, 89, 10, 61, 55}; // get the size of array size_t arraySize = std::size(arr); std::cout << "The size of the array is: " << arraySize << std::endl; return 0; }
Output
Frequently Asked:
The size of the array is: 5
Using the C-style sizeof operator
The sizeof operator in C++ accepts an array as an argument and returns the total memory used by the array in bytes. To get the actual number of elements in the array, we can divide the total size by the size of an individual element (e.g., the size of an integer).
Here’s how you can use the sizeof operator to get the size of an array.
Let’s see the complete example,
#include <iostream> #include <iterator> int main() { // Array of integers with 5 elements int arr[] = {78, 89, 10, 61, 55}; // get the size of array size_t len = sizeof(arr) / sizeof(arr[0]); std::cout << "The size of the array is: " << len << std::endl; return 0; }
Output
The size of the array is: 5
Summary
Both options will give you the number of elements in the array. The std::size() function is more C++ modern and straightforward, while the C-style sizeof operator is a traditional method that can still be used in older C++ versions.
Pointers in C/C++ [Full Course]
Summary
Today, we learned about multiple ways to get the size of an array in C++.