Hi David, Thanks a lot..... :) Thanks & Regards,
Rajath N R --- On Thu, 10/23/08, David Hamill <[EMAIL PROTECTED]> wrote: From: David Hamill <[EMAIL PROTECTED]> Subject: Re: [c-prog] Please help again, bidimensional dynamic array as a global variable To: [email protected] Date: Thursday, October 23, 2008, 3:06 AM Rajath, There are different approaches to representing two-dimensional arrays in C. There's a good discussion in Numerical Recipes in C by Press et al., 2nd edition, if you have access to that. But which is the "best" representation depends on what you're trying to do with the arrays. Where the rows can be of different lengths, as in an array of strings, then it makes sense to use the pointer-to-array- of-pointers approach. This is well explained in Kernighan and Ritchie. An advantage of this representation is that the strings can easily be sorted without moving them: you just move the pointers. In scientific computing, on the other hand, one is usually concerned with matrices. These are 2-D rectangular arrays, usually of floats or doubles. The rows are all of the same size (as are the columns). There is generally no requirement to sort the values. In this case, it makes sense to "unroll" the matrix into a 1-D array. If we have an m x n matrix (m rows, n columns) of doubles, then we can allocate storage in one go: double *mat = NULL; mat = malloc(m * n * sizeof(double) ); assert(mat != NULL); /* ... do stuff ... */ free(mat), mat = NULL; Note that you only need one call to malloc() and one to free(). With your scheme, as well as an allocator you'll have to write a deallocator that iterates through each of the allocated blocks of memory, freeing them in turn. You can't do it with a single free()! That would cause a big memory leak. However, there's no such thing as a free lunch (no pun intended), and a disadvantage of the unrolling approach is that you lose the ability to use the mat[i][j] notation. Instead you have to refer to an array element as: matrix[m*i + j] or *(matrix + m*i + j) which the compiler treats identically. But you could probably write a preprocessor macro to allow notation like mat(i,j). Having said all that, Numerical Recipes in C does actually use a double **mat approach. There are functions that allocate and deallocate memory in a similar way to yours, in nrutil.h and nrutil.c (Appendix B of the book). These are public-domain routines and are online here: http://www.nr. com/public- domain.html Large, sparse matrices are a different matter and need something like a hashtable representation. David [Non-text portions of this message have been removed]
