Define the size of a two dimensional matrix with variables

Hi,

so far i declared matrices with this method:

double *value = new double[numrows] ;
because its dimension (numrows) wasn't always the same, and because

with the method "double values[numrows];" i got the error that the dimension should be constant.

Now i want to define a new 2-D matrix.

I tried method: double

double *value = new double[numrows][numcols] ;
and get message that the expression must have constant value.

Any ideas?
so far i declared matrices with this method:

double *value = new double[numrows] ;


You declared a pointer to double and allocated memory for one-dimensional array.

double *value = new double[numrows][numcols] ;
and get message that the expression must have constant value.


The compiler must know the size of the element of a two-dimensional array. That is in this statement numcols shall be a constant expression. Moreover the types of left and right sides of the expression in the statement do not coinside.

Usually the following method is used

1
2
3
4
5
6
double **value = new double *[numrows];

for ( int i = 0; i < numrows; i++ )
{
   value[i] = new double[numcols];
} 
Last edited on
If your array is going to change size, you would be better off using a list of vectors - that way you can resize the vector and insert new vectors into the list.

Also, in my limited experience, whatever is on the left of the pointer variable should be the same as on the right of new operator like this:

 
MyClass *pMyClass = new MyClass ;

Thank you a lot vlad from moscow!

So, i can refer to value[row][column]?

Is it safe all this?

Yes, you can and it is safe if indexes will not go beyond the acceptable range.
However, keep in mind that the rows are not contiguous in memory.
If that's an issue use new T[rows*columns];
accessing like matrix[K*columns+L] === matrix[K][L] (encapsulate it in a class)

ne555

What kind of issues can arise?
What I mean is `if you do want to be contiguous'. By instance reducing access time because of proximity principle.
By using this method i want to build a 25065 * 44434 matrix. All elements should be double ie. 8 bytes each.

If you do the computations, it will use 8,5 GB RAM, which is too much.

Is there any option to downsize it under 2GB?



Thank you all for your help.
If this huge matrix contains mostly zeros (or some other constant value), then you can consider a sparse matrix : http://en.wikipedia.org/wiki/Sparse_matrix
Other possibilities:
1 - write a matrix class that swaps to disk the parts it won't be needing.
2 - write a matrix class entirely disk-based (sloooow).
3 - a matrix class that stores compressed information (harder).

Topic archived. No new replies allowed.