How to find the size of an array in C++

Here we will see how can we find the size of a given array if the size is not known.

Using sizeof() operator:

The sizeof() operator returns the size of any data type passed to it. Also if we pass the name of the array it returns the total size taken by all elements of the array. So if we want to find the number of elements in the array we have to divide it by the size of each element of the array.

#include<bits/stdc++.h>
using namespace std;

int main(){
    int arr[]={1,2,3,4,5};
    cout<<sizeof(arr)<<endl;    
    return 0;
}
Output: 20

It is because it gives the total size of the array which is the size of one element multiplied by the total number of elements. So to get the actual size (length of the array) we have to divide it by the size of one element.

#include<bits/stdc++.h>
using namespace std;

int main(){
    int arr[]={1,2,3,4,5};
    cout<<sizeof(arr)/sizeof(arr[0])<<endl;    
    return 0;
}
Output: 5

Using pointer arithmetic:

Another way of getting the size of the array can be using pointer arithmetic.

int size = *(&arr+1) - arr;
#include<bits/stdc++.h>
using namespace std;

int main(){
    int arr[]={1,2,3,4,5};
    cout<< *(&arr+1)-arr;    
    return 0;
}
Output: 5

Let’s try to understand how this works:

  • &arr: As we know ‘&‘ operator returns the address of the data type passed to it. So it will return the address of the whole array and the pointer points to the first element.
  • (&arr+1): By pointer arithmetic, we know that on adding 1 to any pointer it shifts by the size of that data type. So the pointer now shifts by the size of the array.
  • *(&arr+1): Type conversion to int* so that we can finally operate it with arr.
  • *(&arr+1)-arr: arr is a pointer that points to the first element of the array. So finally it will return the size of the array.

 

Thanks for reading the article. Kindly leave a comment if there is any doubt. I will clear it as soon as possible.

Leave a Reply

Your email address will not be published. Required fields are marked *