On 13 Nov 2005 11:17:55 -0800,

pa****@gmail.com 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>>