ADVERTISEMENT
ADVERTISEMENT

C - Read and Print your name using malloc().


IncludeHelp 27 June 2016

In this code snippet we will read and print the name using malloc(), when we declare memory using malloc() it is known as dynamic memory allocation.

This code will occupy memory for N length to store name.

C Code Snippet - Read and Print your Name using malloc()

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

int main()
{
	char *name;
	int limit;
	
	limit=30;
	
	//allocate memory dynamically
	name=(char*)malloc(limit*sizeof(char));
	
	printf("Enter name: ");
	
	scanf("%[^\n]s",name);
	//gets(name);
	
	printf("Hi! %s, How are you?\n",name);
	
	//free dynamically allocated memory
	free(name);	// <-- Hey, dont forget.
	return 0;
}
    
    Enter name: Miky Thomas
    Hi! Miky Thomas, How are you?

Learn more Dynamic Memory Allocation tutorial with solved programs.

ADVERTISEMENT




ADVERTISEMENT



Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

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.