2d arrays

John Pfeifer pfeifer at alw.nih.gov
Thu Mar 14 06:23:30 AEST 1991


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:
	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.)

-John
-- 
#include <stdsig.h>

        John Pfeifer                    internet: pfeifer at alw.nih.gov

	"The most creaative and holy of men are always quite mad.
	 It is simply a social thing as to wether one is sane or
	 _insane_."				-The Madonna Vampira



More information about the Comp.lang.c mailing list