Alex Rivera | Logout

Is there a way to initialize an array with non-constant variables? (C++)

Asked 2009-06-09T21:53:57.737
12

I am trying to create a class as such:

class CLASS
{
public:
    //stuff
private:
    int x, y;
    char array[x][y];
};

Of course, it doesn't work until I change int x, y; to

const static int x = 10, y = 10;

Which is impractical, because I am trying to read the values of x and y from a file. So is there any way to initialize an array with non-contant values, or declare an array and declare its size on different statements? And I know this would probably require the creation of an array class, but I'm not sure where to start on this, and I don't want to create a 2D dynamic list when the array itself is not dynamic, just the size is not known at compile-time.

Edit
Report

1 Answer

15

use vector.

#include <vector>
class YourClass
{
public:
    YourClass()
    : x(read_x_from_file()), y(read_y_from_file())
    {
        my_array.resize(x);
        for(int ix = 0; ix < x; ++ix)
            my_array[ix].resize(y);
    }

    //stuff

private:
    int x, y;
    std::vector<std::vector<char> > my_array;
};
answered 2009-06-09T21:59:00.583

Your Answer