[圖解C] Example 721: dynamic allocation of strings

// Example 721: dynamic allocation of strings

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// using strlen() which in <string.h>

int main()
{
    char *name;
    int count;
   
    printf("enter the length of the string: ");
    scanf("%d", &count);
   
    // dynamic allocation
    name = (char*)malloc((count+1)*sizeof(char));
    // count+1: end char '\0' included
   
    printf("enter the string: ");
    scanf("%s", name);       // content of pointer name dep on %s
    printf("the length of ""%s"" is %d\n", name, strlen(name));
    // strlen(name) <= count due to dynamic allocation
   
    system("pause");
    return 0;
}