Open In App

How to Find the Size of an Array Using Pointer to its First Element?

Last Updated : 06 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, arrays are plain old data types that do not have any associated functions to find their size. In this article, we will discuss how we can determine the size of the array in C++ using the pointer to its first element.

Example

Input: 
int arr[]={1,2,3,4,5}

Output:
Size of the array is 5

Find the Size of an Array from a Pointer to its First Element

Unfortunately, there is no way we can find the size of an Array using only the pointer to its first element. Even if we try to use sizeof to that pointer, we will only get the size of the pointer itself but not the array.

We can see that in this example,

C++




// C++ program to illustrate that we cannot find the size of
// the array only using the pointer to its first element
#include <iostream>
using namespace std;
  
int main()
{
    // array
    int arr[] = { 1, 2, 3, 4, 5 };
    // pointer
    int* ptr = arr;
  
    int size = sizeof(ptr);
  
    cout << "The size of the array is: " << size << endl;
  
    return 0;
}


Output

The size of the array is: 8


That is why, it is recommended to use the inbuilt containers like std::vectors, std::arrays, etc. If you still need to use arrays, keep a variable that stores the size of the array.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads