0

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!

3
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by firstPerson
0
//Dynamic 2D memory allocation

float* matrix = NULL;

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

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

Edited by Clinton Portis

1

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
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.