[圖解C] Example 724: using strlen(), strcpy()

// Example 724: using strlen(), strcpy()
// strlen(): counter the length of strings
// strcpy(str1, str2): copy str2 to and after str1
// strlen(), strcpy() in <string.h>

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

int main()
{
    char **month;
    char temp[20];    // temp is an array in (1x20)
    int i;
   
    char name[12][10] = {
             "January", "February", "March", "April", "May", "June",
             "July", "August", "September", "October", "Novermber",
             "December"};
   
    month = (char**)malloc(12*sizeof(char*));
    for (i=0 ; i<12 ; i++){
        // clear the temp
        strcpy(temp, "");
       
        // name -> temp -> month
       
        // copy name to temp
        strcpy(temp, name[i]);
       
        // strlen(array), temp is an array in (1xlength)
        printf("the length of temp (%2dth month): %d\n", i+1, strlen(temp));
       
        month[i] = (char*)malloc((strlen(temp)+1)*sizeof(char));
        // +1 of strlen(temp)+1:  for the end char '\0'
        // (strlen(temp)+1): dynamic allocation of memory by length of month name
       
        strcpy(month[i], temp);
        // copy temp to month[i]
    }
   
    for (i=0 ; i<12 ; i++){
        printf("%2dth = %s\n", i+1, month[i]);
        // the content of pointer month[i] dep on %s
    }
   
    system("pause");
    return 0;
}