la******@yahoo.com wrote:
I have developed my own copy function for coping my own dynamic memory
structure. It works, but I feel its not too efficient. There must be
a quicker way to copy the data. In some of the routines I have
developed the copy function gets called several hundreds of times, with
very large data structures. This can take some time....
Having one contiguous block of memory representing one matrix would
help in creating copies faster. (This is my assumption. Hope that
is valid.)
How about something like this? In my example, I am using two blocks
of memory, one holding the actual data (or the complex numbers) and
the other holding the meta data. Any comments on this are welcome.
It is C code, run through C++ compiler. Converting this into a
suitable C++ class is left as an exercise.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct ComplexNumber
{
float r;
float i;
};
struct Matrix
{
int maxRow;
int maxCol;
size_t size;
ComplexNumber *first;
};
Matrix* matrix_alloc(int row, int col)
{
Matrix* matrix = (Matrix*) malloc( sizeof(Matrix) );
matrix->maxRow = row;
matrix->maxCol = col;
matrix->size = sizeof(ComplexNumber)*row*col;
matrix->first = (ComplexNumber*) malloc( matrix->size );
return matrix;
}
ComplexNumber* matrix_get(Matrix* matrix, int row, int col)
{
int idx = (row* matrix->maxCol)+col;
return matrix->first+idx;
}
void matrix_free(Matrix* x)
{
free(x->first);
free(x);
}
Matrix* matrix_clone(Matrix* orig)
{
Matrix* copy = matrix_alloc(orig->maxRow, orig->maxCol);
memcpy(copy->first, orig->first, orig->size);
return copy;
}
void matrix_print(Matrix *matrix)
{
printf("\n");
for(int i=0; i < matrix->maxRow; ++i)
{
for(int j=0; j< matrix->maxCol; ++j)
{
ComplexNumber* cn = matrix_get(matrix, i,j);
printf("(%f, %f) ", cn->r, cn->i);
}
printf("\n");
}
printf("\n");
}
int main()
{
Matrix *matrix = matrix_alloc(3, 3);
for(int i=0; i <3; i++)
{
for(int j=0; j<3; j++)
{
ComplexNumber* cn = matrix_get(matrix, i,j);
cn->r = i;
cn->i = j;
}
}
Matrix *copy = matrix_clone(matrix);
matrix_print(matrix);
matrix_print(copy);
matrix_free(matrix);
matrix_free(copy);
return 0;
}