Get Amount of Elements In Allocated Array

closed account (zb0S216C)
As in the title, I trying to get the amount of elements within an array that is allocated on the heap. Firstly, here's my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>

using std::cout;
using std::cin;
using std::endl;

template < typename __TYP_SPC__ >
struct BACKINFO
{
    BACKINFO( void ), BACKINFO( const int iElm_count );
    ~BACKINFO( void );

    bool m_bIn_use;
    __TYP_SPC__ *m_ptr_Allocator;
};

template < typename __TYP_SPC__ >
struct BUFFER
{
    BUFFER( void );
    ~BUFFER( void );

    BACKINFO < __TYP_SPC__ > *m_ptr_Allocator;
} Buffer;

template < typename __TYP_SPC__ >
BUFFER < __TYP_SPC__ >::BUFFER( void )
{
    m_ptr_Allocator = new BACKINFO[ 3 ];
}

int main( )
{
    int l_iElem_count( sizeof( Buffer.m_ptr_Allocator ) / sizeof( Buffer.m_ptr_Allocator[ 0 ] ) );

    cout << "Total elements: " << l_iElem_count << endl;

    cin.get( );
    return 0;
}

The thing is, when I print out the number of elements on line 36, 4 is always given. However, I tried creating the array( Referring to: BUFFER::m_ptr_Allocator ) without the new keyword, and it gives me 3. What's going on?

Note: I have missed out some parts of the code that are irrelevant.
The code you show doesn't compile. See https://ideone.com/goRqP. And I understand that: In line 24 you are declaring a variable called Buffer of type.... what type? BUFFER< what? >?

Also note that even if the above compiled, sizeof(Buffer.m_ptr_Allocator) will always return the size of a pointer: 4 bytes in 32-bit machines, 8 bytes in 64-bit machines, so the element count in dynamic arrays cannot be obtained by means of sizeof(). There is no other way: Save the length in a separate variable.
In Windows (maybe Linux has something too), you could call HeapCreate() yourself and use the heap to allocate memory instead of using the new operator. In this case, you could then use HeapSize() (http://msdn.microsoft.com/en-us/library/aa366706(VS.85).aspx) to determine the size in bytes of the allocated block (by HeapAlloc() or HeapRealloc()).
closed account (zb0S216C)
Thank for the reply, WebJose.

I didn't copy and paste the code from the IDE so I may have missed out some pieces of code. As for the HeapCreate( ) suggestion, I'll read upon it now.

Thanks again.
Topic archived. No new replies allowed.