444,225 Members | 2,172 Online Need help? Post your question and get tips & solutions from a community of 444,225 IT Pros & Developers. It's quick & easy.

# Dynamic matrix

 P: n/a Hi all How can I define a dynamic matrix and pass it to a function? Nov 15 '05 #1
3 Replies

 P: n/a wrote in message news:11*********************@g49g2000cwa.googlegro 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

 P: n/a pa****@gmail.com 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 Nov 15 '05 #3

 P: n/a On 13 Nov 2005 11:17:55 -0800, pa****@gmail.com wrote: Hi allHow 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. <> Nov 15 '05 #4

### This discussion thread is closed

Replies have been disabled for this discussion. 