Question

Is there some way to delay defining the size of an array until a class method or constructor?

What I'm thinking of might look something like this, which (of course) doesn't work:

class Test
{
    private:
    int _array[][];

    public:
    Test::Test(int width, int height);
};

Test::Test(int width, int height)
{
    _array[width][height];
}
Was it helpful?

Solution

What Daniel is talking about is that you will need to allocate memory for your array dynamically when your Test (width, height) method is called.

You would declare your two dimensional like this (assuming array of integers):

int ** _array;

And then in your Test method you would need to first allocate the array of pointers, and then for each pointer allocate an array of integers:

_array = new  *int [height];
for (int i = 0; i < height; i++)
{
    _array [i] = new int[width];
}

And then when the object is released you will need to explicit delete the memory you allocated.

for (int i = 0; i < height; i++)
{
    delete [] _array[i];
    _array [i] = NULL;
}
delete [] _array;
_array = NULL;

OTHER TIPS

vector is your best friend

class Test
{
    private:
    vector<vector<int> > _array;

    public:
    Test(int width, int height) :
        _array(width,vector<int>(height,0))
    {
    }
};

I think it is time for you to look up the new/delete operators.

Seeing as this is a multidimensional array, you're going to have to loop through calling 'new' as you go (and again not to forget: delete).

Although I am sure many will suggest to use a one-dimensional array with width*height elements.

(Months later) one can use templates, like this:

// array2.c
// http://www.boost.org/doc/libs/1_39_0/libs/multi_array/doc/user.html
// is professional, this just shows the principle

#include <assert.h>

template<int M, int N>
class Array2 {
public:
    int a[M][N];  // vla, var-len array, on the stack -- works in gcc, C99, but not all

    int* operator[] ( int j )
    {
        assert( 0 <= j && j < M );
        return a[j];
    }

};

int main( int argc, char* argv[] )
{
    Array2<10, 20> a;
    for( int j = 0; j < 10; j ++ )
    for( int k = 0; k < 20; k ++ )
        a[j][k] = 0;

    int* failassert = a[10];

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top