C program to read and print name, where memory for variable should be declared at run time

Dynamic Memory Allocation Example: In this C program, we will declare memory character array (to read name) at run time, will read name and print the string.

This program is an example of Dynamic Memory Allocation, where maximum length of the name (number of characters) to be read at run time, program will declare memory for entered length of the name using malloc(), then program will read the name and print.

Consider the program:

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

int main()
{
    char* name;
    int limit;

    printf("Enter maximum length of name: ");
    scanf("%d", &limit);

    //allocate memory dynamically
    name = (char*)malloc(limit * sizeof(char));

    printf("Enter name: ");
    getchar(); //get extra character to clear input buffer
    gets(name);
    //scanf("%*[^\n]%1*[\n]",name);

    printf("Hi! %s, How are you?\n", name);

    //free dynamically allocated memory
    free(name); // <-- Hey, dont forget.

    return 0;
}

Output

Enter maximum length of name: 30
Enter name: Mayank Singh
Hi! Mayank Singh, How are you?

C Advance Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.