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:


int main()
	char *name;
	int limit;
	printf("Enter maximum length of name: ");
	//allocate memory dynamically
	printf("Enter name: ");
	getchar(); //get extra character to clear input buffer
	printf("Hi! %s, How are you?\n",name);
	//free dynamically allocated memory
	free(name);	// <-- Hey, dont forget.
	return 0;


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.

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.