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

后端 未结 9 2121
無奈伤痛
無奈伤痛 2020-12-06 11:20

I am trying to create a class as such:

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

Of course, it does

9条回答
  •  既然无缘
    2020-12-06 11:57

    You can allocate memory to your 2-dimensional array in the constructor and free it in the destructor. The simplest way:

    array = (char **)malloc(sizeof(char *) * x);
    if (array) {
        for (i = 0; i < x; i++) {
            array[i] = (char *)malloc(sizeof(char) * y);
            assert(array[i]);
        }
    }
    

提交回复
热议问题