Friday, 23 August 2013

Is a 2d array set up in memory contiguously similar to a 1d array simulating a 2d one?

Is a 2d array set up in memory contiguously similar to a 1d array
simulating a 2d one?

Consider the 2 type of array declarations:
T *x = new T[rows * cols]; // type 1
T *y = new T[rows][cols]; // type 2
I usually use the first type ( type 1) where then I know to index using
x[row * cols + col]
however if I want to copy a 2d array into a 1d array simulating a 2d array
ie: copy type2 -> type1. If these are guaranteed to be laid out the same
way in memory can I just do a memcpy of one to the other? Currently I have
a loop as such but if the memory is the same layout in both I am thinking
I can just do a memcpy. Consider the following public constructor below.
public:
// construct a matrix from a 2d array
template <unsigned int N, unsigned int M>
Matrix ( T (&twoDArray)[N][M] ) : rows_(N), cols_(M), matrixData_(new
T[rows_*cols_])
{
// is there a refactor here? Maybe to memcpy?
for ( unsigned int i = 0; i < rows_ ; ++i )
{
for ( unsigned int j = 0; j < cols_ ; ++j )
{
matrixData_[ i * cols_ + j ] = twoDArray[i][j];
}
}
}
private:
unsigned int rows_;
unsigned int cols_;
T* matrixData_;

No comments:

Post a Comment