Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delaying array size in class definition in C++?

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];
}
like image 261
slythfox Avatar asked Mar 05 '09 06:03

slythfox


2 Answers

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;
like image 99
RedBlueThing Avatar answered Nov 15 '22 05:11

RedBlueThing


vector is your best friend

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

    public:
    Test(int width, int height) :
        _array(width,vector<int>(height,0))
    {
    }
};
like image 43
Artyom Avatar answered Nov 15 '22 05:11

Artyom