Question: malloc on 2-D array

David Geary dmg at ssc-vax.UUCP
Thu Jul 13 05:36:24 AEST 1989


In article <15372 at eecae.UUCP>:

+  Does anyone know how I can allocate memory space for a multi-dimensional
+  array?  Thanks in advance.

  I would've emailed this, except that I've seen this request often enough
to justify a posting.  Anyway, the code below contains functions needed
to allocate a 2D array of characters.

  stringAlloc() is a trivial function that allocates size number of 
characters, and returns a pointer to the newly allocated memory.  This
function could also be implemented as a macro.

  stringArrayAlloc() allocates a 2D array, using stringAlloc() to allocate
the individual characters for each string in the "array".  Notice that this
function needs to know 2 things:  how many char*'s to allocate, and how
many char's to allocate for each char* allocated (does that make sense? ;-)

  It is easy to extend this to a 3D array of chars, or, for that matter,
4D or 5D, or whatever.  It is also trivial to derive functions that
will allocate arrays of ints, floats, or any other data type.

#include <stdio.h>

#define memalloc(type, size)   ( (type *)malloc(size * (sizeof(type))) )

/*
*
* char  *stringAlloc(int size)                                          
*                                                                      
*    This function allocates enough memory to hold size number of characters 
*  (plus the NULL).  The function then returns a poniter to the newly allocated
*  memory (if malloc() was successful), or NULL (if the allocation failed).     *
*/

char *stringAlloc(size)                             
int   size;				       
{
  char *returnme = NULL;             /* we'll return this pointer.         */ 
  
  returnme = memalloc(char, size+1); /* allocate size + 1 (for NULL)       */ 
  return returnme;                   /* return valid addr, or NULL         */
}

/*
*
*  char  **stringArrayAlloc(int numStrings, int *sizes)                         *
*    This function first of all allocates an array of pointers to char.  Then, 
*  for each pointer to char allocated, stringAlloc() is called to allocate 
*  a certain number of characters.  Finally, a char** is returned, 
*  (or NULL if the initial allocation failed).  
*                                              
*/
char **stringArrayAlloc(numStrings, sizes)
  int   numStrings;                         /* How many strings to alloc?
  int*  sizes;                              /* array of sizes for strings  */

  char **returnme = NULL;                   /* return this pointer.        */
  int    cnt;

  if(returnme = memalloc(char*, numStrings)) /* Alloc array of char*'s      */
  {                                          /* If allocation worked,...    */
    for(cnt=0; cnt < numStrings; ++cnt)      /* for each char* allocated,   */
      returnme[cnt] = stringAlloc(*sizes++); /* allocate room for chars.    */
  }
  return returnme;                           /* rtn valid addr, or NULL     */
}
  
testStringAlloc()
{
  char *str = stringAlloc(10);  /* allocate 11 bytes, and point str to it    */

  strcpy(str, "123456789*");    /* copy string into newly allocated memory   */
  puts(str);                    /* show string.                              */

  free(str);                    /* now free the string from memory           */
}

#define NUM_STRINGS 4

testStringArrayAlloc()
{
  static int stringSizes[] = { 5, 10, 15, 20 };  /* sizes for strings       */
  int        cnt;                            
  char      **stringArray;   

  stringArray = stringArrayAlloc(NUM_STRINGS, stringSizes);

  strcpy(stringArray[0], "12345");              /* copy stuff into strings */
  strcpy(stringArray[1], "123456789*");
  strcpy(stringArray[2], "123456789*12345");
  strcpy(stringArray[3], "123456789&123456789*");

  puts(stringArray[0]);                         /* show strings...         */
  puts(stringArray[1]);
  puts(stringArray[2]);
  puts(stringArray[3]);

  free(stringArray[0]);                         /* free strings            */
  free(stringArray[1]);
  free(stringArray[2]);
  free(stringArray[3]);
  free(stringArray);                            /* free char*'s            */
}  

main()
{
  testStringAlloc();
  testStringArrayAlloc();
}
-- 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~ David Geary, Boeing Aerospace, Seattle                 ~ 
~ "I wish I lived where it *only* rains 364 days a year" ~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~



More information about the Comp.lang.c mailing list