Dynamically Allocating a Multidimensional Array source code

This snippet submitted by Jared Hendrickson on 2005-11-02. It has been viewed 4910 times.
Rating of 6.2 with 10 votes

#include <stdio.h>

char **createMultiD(int subscriptOne, int subscriptTwo);

int main(void)
{
    char **multi;
    
    multi = createMultiD(5, 5);
    
    /* multi can now be treated as a multidimensional array */
    
    multi[4][4] = 'X';
    
    printf("%c\n", multi[4][4]);
}

/* The actual function */

char **createMultiD(int subscriptOne, int subscriptTwo)
{
     char **multi;
     int ctr = 0;
     
     /* Assigns an array of pointers to multi. */
     /* This acts as the first array subscript. */
     multi = (char **)malloc(sizeof(char *) * subscriptOne);
     
     if(multi == NULL)
     {
              /* Immediate termination of the function */
              return(multi);         
     }
     
     /* Assigns an array of characters to each pointer in multi. */
     /* This acts as the second array subscript. */
     for(ctr = 0; ctr <= subscriptTwo; ctr++)
     {
             multi[ctr] = (char *)malloc(sizeof(char) * subscriptTwo);
     }
     
     return(multi);
}
 




More C and C++ source code snippets

Add a snippet!