Multi-dimensional Array via malloc()

◀ Differences between Arrays and Pointers▶ Multidimensional Array via new Operator
Amazon malloc() is a popular library function in C. A programmer knowing how to use malloc() has no problem creating a one-dimensional array. However, what about two-dimensional or even three-dimensional array? The point of using malloc() is to dynamically allocate space because in some situations the programmer has no way of knowing how many variables he needs until later.

Here is an example of how to use malloc() to create a two-dimensional array:
char **peers;
peers=(char**)malloc(3*sizeof(char*)); /* peers contains 3 char* */ peers[0]=”the first one”; /* initialize the first char* */ peers[1]=”the second one”; /* initialize the second char* */ peers[2]=”the third one”; /* initialize the third char* */
As we can see, peers is a two-dimensional array, but how are the data stored? For example, what will peers[0][5] give you? It will give you the letter “i” because it is the sixth letter in peers[0].

For those who are still confused by the way malloc() works here is an example of how to use malloc() to create a three-dimensional array:

char ***peers;
peers=(char***)malloc(3*sizeof(char**));	/* peers contains 3 char** */
peers[0]=(char**)malloc(3*sizeof(char*));	/* peers[0] contains 3 char* */
peers[1]=(char**)malloc(4*sizeof(char*));	/* peers[1] contains 4 char* */
peers[2]=(char**)malloc(5*sizeof(char*));	/* peers[2] contains 5 char* */

/* initialize all char* variables, 12 total */
peers[0][0]="guys";
peers[0][1]="it";
peers[0][2]="all";
peers[1][0]="comes";
peers[1][1]="down";
peers[1][2]="to"; peers[1][3]="dealing"; peers[2][0]="with"; peers[2][1]="people"; peers[2][2]="david"; peers[2][3]="and"; peers[2][4]="jim";
If you want to deallocate memory allocated by using malloc(), use free(), not delete!
◀ Differences between Arrays and Pointers▶ Multidimensional Array via new Operator

fShare
Questions? Let me know!