Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get the size of heap array in c++ [duplicate]

Code1:

int * a;
a=new int[222];
cout<<"the size of a is "<<sizeof(a)<<endl;

Output1:

the size of a is 8

Code2:

int * a;
a=new int[222];
cout<<"the size of a is "<<a.length()<<endl;

Output2:

error: member reference base type 'int *' is not a structure or
  union

How to get the size of a heap array? Thanks..

like image 889
spicyShoyo Avatar asked Dec 04 '25 13:12

spicyShoyo


2 Answers

The short answer is, it can't be done, at least not in a portable manner. You'll need to keep track of the array's size separately somehow (e.g. in an integer variable or similar).

like image 106
Jeremy Friesner Avatar answered Dec 07 '25 04:12

Jeremy Friesner


Use a container instead of a raw pointer:

std::vector<int> a(222);
cout << "the size of a is " << a.size(); << endl;
like image 28
M.M Avatar answered Dec 07 '25 04:12

M.M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!