Hello, guys.

This is the fragment of my program. I can't initialize the dynamic two-dimensional array. The compiler says to me that 'y' cannot appear in a constant - expression. But I need that both x and y to be dynamic. How can I fix that?

`

float a;
int x, y, uSize;

do
{
cout << "Enter the size of matrix " << endl;
cin >> uSize;
}
while (uSize > 0);

x = y = uSize;

float *userMatrix = new float[x][y];

`

Thanks for your time!

//Dynamic 2D memory allocation

float* matrix = NULL;

float** userMatrix = new matrix*[10];

for (int i=0; i<10; i++)
{
     *userMatrix[i] = new matrix;
}

I think the syntax is

int rowSize = 5;
int colSize = 5;
float **matrix = new float*[rowSize];
for(int i = 0; i < rowSize; ++i){
  matrix[i] = new float[colSize];
}

//do stuff with matrix[i][j]

//delete
for(int i = 0; i < rowSize; ++i){
   delete [] matrix[i];
}
delete [] matrix;

Of course you can avoid all of this by using std::vector.

  int rowSize = 5;
  int colSize = 5;
  std::vector< std::vector<float> > matrix( rowSize, std::vector<float>(colSize) );

  //use matrix[i][j]

  //no need to worry about deleting matrix
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.