Home » C programs

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?





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.