Question: malloc on 2-d array

Gordon C. Galligher gorpong at telxon.uucp
Wed Jul 12 02:23:30 AEST 1989


In article <15372 at eecae.UUCP> pantz at brain.mth.msu.edu writes:
>
>Does anyone know how I can allocate memory space for a multi-dimensional
>array?  Thanks in advance.

(In the following examples, you can substiture your favorite pointer in 
place of the char *'s):

On some systems the calloc() call is allowed.  You declare a variable:

	char **a, *calloc();
	
	if ( (a = (char **) calloc(25, sizeof(char *))) == NULL )
		error_message_here;

This will allocate at least enough memory to be used like an array of 25 
elements, each element being a pointer to a character.  To put strings INTO 
these places, then you need to call malloc() for each a[x] you want to store.

If calloc() doesn't exist, then you can coerce malloc() into doing it for you:

	char **a, *malloc();
	
	if ( (a = (char **) malloc((25 * sizeof(char *)))) == NULL )
		error_message_here;

Again, the malloc() for each a[x] is needed.

		-- Gordon.
Gordon C. Galligher  <|> ...!uunet!telxon!gorpong <|> gorpong at telxon.uucp.uu.net
Telxon Corporation   <|> "Admit it, ve're lost!"  - Checkov  "Alright, we're 
Akron, Ohio, 44313   <|>  lost, but we're making great time."  - Sulu
(216) 867-3700 (3512)<|>         Star Trek V:  The Final Frontier



More information about the Comp.lang.c mailing list