Velocity Reviews > Dynamic matrix

# Dynamic matrix

paytam@gmail.com
Guest
Posts: n/a

 11-13-2005
Hi all
How can I define a dynamic matrix and pass it to a function?

Malcolm
Guest
Posts: n/a

 11-13-2005

<(E-Mail Removed)> wrote in message
news:(E-Mail Removed) ups.com...
> 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[i] = 0.0;
for(i=0;i<size;i++)
mtx[i*size+i] = 1.0;
}

Emmanuel Delahaye
Guest
Posts: n/a

 11-13-2005
http://www.velocityreviews.com/forums/(E-Mail 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.

--
A+

Emmanuel Delahaye

Barry Schwarz
Guest
Posts: n/a

 11-13-2005
On 13 Nov 2005 11:17:55 -0800, (E-Mail Removed) wrote:

>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[i][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>>