Calloc( ).

closed account (zb0S216C)
I started to learn about calloc( ); today. When I created an array with calloc( ); I was wondering, "How do I access each of the elements I created?".

Heres what I got so far:
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
template < typename Type >
class NewArray
{
    public:
        NewArray( unsigned uNewLength )
        {
            Array = ( Array * )calloc( uNewLength, sizeof( Type ) );
        }

        ~NewArray( void )
        {
            free( Array );
            Array = NULL;
        }
 
        void Release( void )
        {
            // Release the array here...
        }

        Type GetValue( unsigned uIndex )
        {
            // Access the specified element, but how?
        }
    protected:
        Type *Array;
};
You should not use calloc -- especially not in templates. calloc is similar to malloc. Neither one of them will call the constructor of whatever object you're allocating, meaning they will only work for POD types. If you try to calloc something like a string, or some other complex type it will fail spectacularly.

In C++, stick with new[] and delete[] for dynamic allocation (or better yet, just use something like vector). malloc/calloc are remnants of C.
Last edited on
closed account (zb0S216C)
All right then, I won't use it anymore. Thanks Disch.
Topic archived. No new replies allowed.