Next: Strings
Up: C++/C
Previous: C++/C
There are several options for allocating memory for matrices and higher-dimensional
arrays. Memory can be allocated statically or dynamically and contiguously
or not contiguously. Library routines typically need array elements
to be contiguous in memory.
- Static contiguous:
double foo[numcol*numrow];
foo[col+row*numcol]=0.0;
- Static not contiguous
double foo[numrow][numcol]
foo[row][col]=0.0;
- Dynamic contiguous:
double* foo=new double[numcol*numrow];
foo[col+row*numcol]=0.0;
delete [] foo;
- Dynamic not-contiguous:
double** foo=new (double*)[numrow];
for(int i=0;i<numrow;i++){
foo[i]=new double[numcol];
}
foo[row][col]=0.0;
for(int i=0;i<numrow;i++){
delete [] foo[i];
delete [] foo;
Notice that for contiguous arrays, you need to calculate the location
of the element of interest. There is a trick for getting around this:
double* tmp=new double[numcol*numrow];
double** foo=new (double*)[numrow];
for(int i=0;i<numrow;i++){
foo[i]=&(tmp[i*numcol]);
}
// now foo[i] is a pointer to the start of each row, and
we can use row,col indexing
foo[row][col]=0.0;
delete [] tmp; // delete with a single call
// plus, we can pass foo to routines requiring a contiguous
array
Chris Paciorek
2012-01-21