next up previous
Next: Strings Up: C++/C Previous: C++/C

Memory allocation

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.

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