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 %26lt;%26lt; "Number of rows:";
int r;
cin %26gt;%26gt; r;
cout %26lt;%26lt; "Number of columns:";
int c;
cin %26gt;%26gt; 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.
C++ matrix operations?
Here is how to create multidimensional arrays in C++:
typedef float* FloatArray;
int main( )
{
int rows = 0;
int columns = 0;
cout %26lt;%26lt; "Number of rows: ";
cin %26gt;%26gt; rows;
cout %26lt;%26lt; "Number of columns: ";
cin %26gt;%26gt; columns;
FloatArray *mat1 = new FloatArray[rows];
FloatArray *mat2 = new FloatArray[rows];
FloatArray *mat3 = new FloatArray[rows];
for(int i = 0; i %26lt; 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 %26lt; rows; i++)
{
delete[ ] mat1[i];
}
delete[ ] mat1;
I hope this helps!!
Reply: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
salary survey
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment