Size of an Array in C++
In C++, we do not have the length function as in Java to find array size but we can calculate the size of an array using sizeof() operator trick. First, we find the size occupied by the whole array in the memory and then divide it by the size of the type of element stored in the array. This will give us the number of elements stored in the array.
data_type size = sizeof(Array_name) / sizeof(Array_name[index]);
Example 3: The C++ Program to Illustrate How to Find the Size of an Array
// C++ Program to Illustrate How to Find the Size of an
// Array
#include <iostream>
using namespace std;
int main()
{
int arr[] = { 1, 2, 3, 4, 5 };
// Size of one element of an array
cout << "Size of arr[0]: " << sizeof(arr[0]) << endl;
// Size of array 'arr'
cout << "Size of arr: " << sizeof(arr) << endl;
// Length of an array
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Length of an array: " << n << endl;
return 0;
}
Output
Size of arr[0]: 4 Size of arr: 20 Length of an array: 5
C++ Arrays
In C++, an array is a data structure that is used to store multiple values of similar data types in a contiguous memory location.
For example, if we have to store the marks of 4 or 5 students then we can easily store them by creating 5 different variables but what if we want to store marks of 100 students or say 500 students then it becomes very challenging to create that numbers of variable and manage them. Now, arrays come into the picture that can do it easily by just creating an array of the required size.