Gold mine of Visual C++ tricks!
Archive for June 18, 2008
How to find the size of dynamically allocated array?
Jun 18th
![]()
While passing dynamically allocated arrays to functions, we usually pass the pointer and size of array. Its because we cannot identify how many members are be present in the allocated array. It will be nice to find the size of array from the pointer itself so that we can eliminate that extra variable. But is it possible? Yes, you can find the size of array from pointer itself. But how?
![]()
You can use _msize(). If you give a pointer, it will return back the allocated size in bytes. See the sample code snippet below.
// Allocate some objects. CRect* pRectArray = new CRect[50]; ... // Calculate the array size from pointer. int ArraySize = _msize( pRectArray ) / sizeof( CRect );
![]()
Note that this is microsoft extension and is not the part of standard C++. Now throw away that extra size parameter from your functions.
![]()
Targeted Audience – Intermediate.