2d arrays

Christopher R Volpe volpe at camelback.crd.ge.com
Thu Mar 14 23:36:58 AEST 1991


In article <1065 at nih-csl.nih.gov>, pfeifer at alw.nih.gov (John Pfeifer) writes:
|>In article <1991Mar13.183807.23254 at ux1.cso.uiuc.edu>,
sasg0244 at uxa.cso.uiuc.edu (Steven Arthur Sivier) writes:
|>|> 
|>|> i've always tried to avoid 2d arrays, but because of a library
|>|> function i need to call i need to use 2d arrays. the problem
|>|> is i have to malloc the 2d array. can i just malloc the array
|>|> to a char pointer and then use it as a 2d array? that is, if
|>|> the array has dimensions x by y can i use:
|>|> 	char *array;
|>|> 	array = malloc(x * y);
|>|> 	array[0][0] = 'a'
|>
|>If I understand you correctly, no.  
|>char[][] is an array of arrays, ie. **char  Try:
  ^^^^^^^^                            ^^^^^^This is not the same thing as
  This is not valid C.                      an array of arrays.
                                        
|>	char **array;
|>	array = malloc(x*sizeof(*char));
|>	for(i=0;i<x;i++)
|>		array[i] = malloc(y*sizeof(char));
|> 
|>|> also, inasmuch as i need to pass this array to a library function,
|>|> can i just send the pointer even though the function expects a
|>|> 2d array?
|>
|>Yes.
|>See section A8.6.2 in K&R (2nd ed.)

No. The two step malloc method you used will allow you to reference the
object as if it were a 2D array, i.e., you can say "array[a][b]" and it
will work, but the storage is not laid out like a true 2D array that you
would declare with "char array[DIM1][DIM2];". If you pass your
"char **array" to a library routine that expects a true 2D array, it will
choke big time.
                                 
==================
Chris Volpe
G.E. Corporate R&D
volpecr at crd.ge.com



More information about the Comp.lang.c mailing list