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.




Comments and Discussions!

Load comments ↻






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