[圖解C] Example 723: dynamic allocation of 2D array(2)

// Example 723: dynamic allocation of 2D array(2)
// array[n][m]
//   type **pointer = (type**)malloc(n*sizeof(type*));
//     pointer[0] = (type*)malloc(m*sizeof(type));
//     pointer[1] = (type*)malloc(m*sizeof(type));
//     pointer[.] = (type*)malloc(m*sizeof(type));
//     pointer[m-1] = (type*)malloc(m*sizeof(type));
//
// using "for" loop to product a pointer in (n x m)

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char **month;
    int i;
   
    char name[12][20] =
       {"January", "February", "March", "April", "May", "June",
        "July", "August", "September", "October", "Novermber", "December"};
   
    // using for-loop to product a pointer in (row x col)
    // dynamic allocation of memory
    month = (char**)malloc(12*sizeof(char*));
    for (i=0 ; i<12 ; i++){
        month[i] = (char*)malloc(10*sizeof(char));
        month[i] = name[i];    // assign a value to pointer[i]
    }
    // pointer[12][10] >> waste memory if the length of month name < 10
   
    for (i=0 ; i<12 ; i++){
        printf("%2dth month = %s\n", i+1, month[i]);
    }
   
    // release memory
    free(month);
   
    system("pause");
    return 0;
}