How to get the size of an array?

How to get the size of an array?
1
2
3
    int *a;
   a=new int[100];//the size of the array is 100
//but sizeof(a) is 4. returned the size of a pointer.how to get 100 returned? 
To see the code and remember the number 100.
you can't. Use std::vector instead.

1
2
3
4
#include <vector>
//...
std::vector<int> a(100);
//a.size(); returns 100 


These days, one can use std::array, the size function returns the number of elements in the array.

Although this is rather silly, because the array size is still a compile time constant, so one should know what it is any way. The other functions available for std::array could be handy though.

http://www.cplusplus.com/reference/array/array/size/
Last edited on

To see the code and remember the number 100.


lol...the best solution!! ^_^


you can't. Use std::vector instead.


Thanks, maybe this is the only way.
Last edited on
There is such a function as std::extent in C++. You can use it to determine the size of an array. But in any case it will not give you the size of a dynamically allocated array.
For example

int a[2][4][6];

std::cout << std::extent<decltype( a )>::value << std::endl;
std::cout << std::extent<decltype( a ), 1>::value << std::endl;
std::cout << std::extent<decltype( a ), 2>::value << std::endl;
std::cout << std::endl;
Last edited on
Topic archived. No new replies allowed.