Q:

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

0

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

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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?

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C language important programs ( Advance Programs )

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to declare memory for an integer variabl... >>
<< C program to find sum of array elements using Dyna...