Dynamic matrix

M

Malcolm

Hi all
How can I define a dynamic matrix and pass it to a function?

/*
caller
*/

/* for the sake of argument, make the matrix 20 x 20 */
int N = 20;
double *ptr = malloc(N * N * sizeof(double));

setidentity(ptr, N);

/* do all sorts of wonderful thngs with your matrix here */
/* free after you have finished with it */
free(ptr);
/*
function - sets a square matrix to identity (all zero except the main
diagonal)
*/
void setidentity(double *mtx, int size)
{
int i;

for(i=0;i<size * size;i++)
mtx = 0.0;
for(i=0;i<size;i++)
mtx[i*size+i] = 1.0;
}
 
E

Emmanuel Delahaye

(e-mail address removed) a écrit :
Hi all
How can I define a dynamic matrix and pass it to a function?

Use a structure to gather the relevent information.

struct mat2d
{
/* array of y pointers to arrays of x T */
T **p;
size_t x;
size_t y;
};

or the linear way :

struct mat2d
{
/* array of (y * x) T */
T *p;
size_t x;
size_t y;
};

and provide a function to access the data.
 
B

Barry Schwarz

Hi all
How can I define a dynamic matrix and pass it to a function?

There are two common approaches. For N rows with M columns each:

One is to simulate the matrix with a one-dimensional array. You
allocate space for N*M objects, as with
T *ptr = malloc(N * M * sizeof *ptr);
and you reference the (i,j)th element by calculating the appropriate
subscript yourself, as in
ptr[i*M+j] = 0;

The other is to build an array of pointers, each pointing to one
row of the matrix, as in
T **ptr = malloc(N * sizeof *ptr);
for (k = 0; k < N; k++)
ptr[k] = malloc(M * sizeof *ptr[k]);
and you reference the (i,j)th element using the natural syntax, as in
ptr[j] = 0;

In either case, you pass the array to a function by using the ptr
variable. Note, since N and M are not known until run time:

Using the first approach always requires M to be available to the
function.

In either approach, the function will need both N and M if it is
concerned in any way with the top or right boundary elements of the
matrix.

The second approach is more flexible in that it can handle jagged
arrays where M is not constant for each row.


<<Remove the del for email>>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top