Open In App

How to Find the Size of a Dynamically Allocated Array in C++?

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

In C++, dynamic memory allocation enables the users to manage the memory resources during the execution of the program and is very useful for arrays when the size of the array is not known at compile time or during any other times for flexibility. In this article, we will learn how to find the size of a dynamically allocated array in C++.

Finding the Size of a Dynamically Allocated Array in C++

Unfortunately, when we dynamically allocate an array using the new keyword, the size of the array is not stored. Also, unlike static arrays where the name of the arrays refers to the whole array, dynamic arrays are stored as pointers so we cannot use the sizeof operator with dynamic arrays.

Therefore, there is no direct way to find the size of a dynamically allocated array. To manage the size of a dynamically allocated array, we must keep track of the size separately. The below program demonstrates one method where we track the size of an array in a separate variable.

C++ Program to Keep the Track of Dynamically Allocated Array

C++




// C++ program to keep track of dynamically allocated array
#include <iostream>
using namespace std;
  
int main()
{
    int size = 5; // size of the array
    int* arr = new int[size]; // dynamically allocated array
  
    // fill the array
    for (int i = 0; i < size; i++) {
        arr[i] = i;
    }
  
    // print the array
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
  
    delete[] arr; // delete the array to avoid memory leak
  
    return 0;
}


Output

0 1 2 3 4 

Note: Generally, vectors are used when the size of the array is not known and we want to get access to the size during the runtime.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads