Dynamically Allocating a Multidimensional Array

Submitted by:David Villa

Date added:26 July, 2015

Category:C

C Code snippet for Dynamically Allocating a Multidimensional Array

Tags: multidimensional array , allocating

Code Snippet:

#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);
}
 
 

Comments