English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I am writing a program to do simple matrix operations. but i want the dimensions of the matrix to be fed by the user. the code below, gives the following error during compile time...

`cols' cannot appear in a constant-expression

cout << "Number of rows:";
int r;
cin >> r;
cout << "Number of columns:";
int c;
cin >> c;

const int rows=r;
const int cols=c;

// Assign dimensions
float* mat1[rows][cols]; float* mat2[rows][cols]; float* mat3[rows][cols];

mat1= new float [rows][cols];
mat2= new float [rows][cols];
mat3= new float [rows][cols];

it works fine if they are 1 dimensional arrays, so why doesnt it compile if i use 2 dimensions. please help.

2007-03-21 15:44:08 · 2 answers · asked by aswan k 1 in Computers & Internet Programming & Design

2 answers

Here is how to create multidimensional arrays in C++:

typedef float* FloatArray;

int main( )
{
int rows = 0;
int columns = 0;

cout << "Number of rows: ";
cin >> rows;
cout << "Number of columns: ";
cin >> columns;

FloatArray *mat1 = new FloatArray[rows];
FloatArray *mat2 = new FloatArray[rows];
FloatArray *mat3 = new FloatArray[rows];

for(int i = 0; i < rows; i++)
{
mat1 = new float[columns];
mat2 = new float[columns];
mat3 = new float[columns];
}

return 0;
}

// To initialize or assign a value to any of the arrays' cells do the following:

mat1[rowNumber][columnNumber] = someValue;

By the way, don't forget to delete the dynamic arrays after you are done with them. Here is how to do that:

for(int i = 0; i < rows; i++)
{
delete[ ] mat1[i];
}
delete[ ] mat1;

I hope this helps!!

2007-03-21 18:25:28 · answer #1 · answered by Silver_Sword 3 · 0 0

the reason it doesn't work is simply because you can't allocate a two dimension array that way it works for one dimension also you could have just wrote that code in one line not that it matters

float * mat1 = new float[rows][cols];

sorry couldn't give you a better help just still don't under C++ that well yet

2007-03-21 18:28:36 · answer #2 · answered by the man the myth the answerer 5 · 0 0

fedest.com, questions and answers