Topic : C-Language Documentation Author : John Kormylo Version : C.HYP 1.0 Subject : Documentation/C-Language Nodes : 233 Index Size : 6362 HCP-Version : 3 Compiled on : Atari @charset : atarist @lang : en @default : @help : Help @options : +g -i -s +x +z -t4 @width : 75 View Ref-File[ Pointer Arrays ] FORTRAN programmers might be dismayed by the fact that C does not support variable dimensions for 2 (or more) dimensional arrays: float trace(int n, float a[n][n]); /* NOT ALLOWED! */ However, an effective substitute is to use a pointer array. For example, if an array of pointers 'float *pa[]' were initialized using for(i=0; i<n; i++) pa[i] = a[i]; /* &(a[i][0]) */ then one could use 'pa[i][j]' in place of 'a[i][j]' in any expression, and float trace(int n, float *pa[]); is legal! And while this technique uses more RAM, it compensates with much faster execution speeds. The following function will allocate space for a 2 dimensional array and initialize a pointer array for it. (You can copy and paste it directly from the Help window.) /* Allocate a 2 dimensional array and return a pointer array[n] */ void* array_alloc( const int n, /* first dimension */ const long size) /* sizeof(type) * second dimension */ { char **a, *p; int i; a = malloc(n * (sizeof(char*) + size)); if(!a) return(0L); /* not enough RAM */ p = (char*) (a + n); for(i=0; i<n; i++, p += size) a[i] = p; return(a); } which can be called using float **a; ... a = array_alloc(n, m * sizeof(float)); for(i=0; i<n; i++) for(j=0; j<m; j++) a[i][j] = 0.0; ... free(a); Note: Use 'a[0]' instead of 'a' in functions which expect the array itself (like memset).