/********************************* ** File 2darray.c ** Author: S. Evans ** Date: 10/31/06 ** Section: 02XX & 201H 0101 ** E-Mail: bogar@cs.umbc.edu ** ** This file demonstrates dynamic memory ** allocation of a 2 dimensional array ** of chars *******************************/ #include #include /*************** ** Function: GetTwoDSpace() ** ** GetTwoDSpace() gets the memory space needed to hold the 2 dimensional ** array of ints and returns the pointer which will become the name of ** the array. ** ** Inputs: Number of rows to be in the array ** Number of columns to be in the array ** Output: The pointer to the memory ********************************/ char **GetTwoDSpace(int rows, int cols) { char **array; int i; /* Get the space for the array of pointers to int */ array = (char**)malloc(rows * sizeof(char*)); if(array == NULL) { fprintf(stderr, "Error getting space for 2-d array of ints\n"); exit(-1); } /* Get the space for all of the one dimensional arrays of ints */ for(i = 0; i < rows; i++) { array[i] = (char*)malloc(cols * sizeof(char)); if(array[i] == NULL) { fprintf(stderr, "Error getting space for 2-d array of ints\n"); exit(-1); } } return array; } /*************** ** Function: FreeTwoDSpace() ** ** FreeTwoDSpace() frees the memory space of a 2 dimensional ** array of ints. ** ** Inputs: Number array to be freed ** Number of rows in the array ** Output: None ********************************/ void FreeTwoDSpace(char **array, int rows) { int i; for(i = 0; i < rows; i++) { free(array[i]); } free(array); }