Gold mine of Visual C++ tricks!
How to find the size of dynamically allocated array?
![]()
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.
| Print article | This entry was posted by Jijo Raj on June 18, 2008 at 7:43 pm, and is filed under Codeproject, Windows APIs. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |