How to get size of dynamic array in C++ [duplicate]

Code for dynamic array by entering size and storing it into "n" variable, but I want to get the array length from a template method and not using "n".

int* a = NULL;   // Pointer to int, initialize to nothing.
int n;           // Size needed for array
cin >> n;        // Read in the size
a = new int[n];  // Allocate n ints and save ptr in a.
for (int i=0; i<n; i++) {
    a[i] = 0;    // Initialize all elements to zero.
}
. . .  // Use a as a normal array
delete [] a;  // When done, free memory pointed to by a.
a = NULL;     // Clear a to prevent using invalid memory reference.

This code is similar, but using a dynamic array:

#include <cstddef>
#include <iostream>
template< typename T, std::size_t N > inline
std::size_t size( T(&)[N] ) { return N ; }
int main()
{
     int a[] = { 0, 1, 2, 3, 4, 5, 6 };
     const void* b[] = { a, a+1, a+2, a+3 };
     std::cout << size(a) << '\t' << size(b) << '\n' ;
}

You can't. The size of an array allocated with new[] is not stored in any way in which it can be accessed. Note that the return type of new [] is not an array - it is a pointer (pointing to the array's first element). So if you need to know a dynamic array's length, you have to store it separately.

Of course, the proper way of doing this is avoiding new[] and using a std::vector instead, which stores the length for you and is exception-safe to boot.

Here is what your code would look like using std::vector instead of new[]:

size_t n;        // Size needed for array - size_t is the proper type for that
cin >> n;        // Read in the size
std::vector<int> a(n, 0);  // Create vector of n elements initialised to 0
. . .  // Use a as a normal array
// Its size can be obtained by a.size()
// If you need access to the underlying array (for C APIs, for example), use a.data()

// Note: no need to deallocate anything manually here