Sunday, September 14, 2014

Display the user input names by allocating memory dynamically (malloc function)


Problem

Write a program that asks the user to input name of students and then displays these names on computer screen. You have to write a program such that it should work with any numbers of names. e.g. users can input 6 names or 100 names.
  1. For such problems declare an array of pointers to characters.
  2. Input a name from user in a temp array of size 50 using gets( ) function. Then allocate a dynamic memory to store that name and assign the base address of dynamic memory to the first index of array of pointers.   
  3. Do the processes in b again and again until the user input an empty string.
  4.  Then displays all the names using array of pointers

Solution - Code

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include <string.h>
int main ()
{
 char *name[30];
 char temp[30];
 int i, k;

 printf ("Enter names: ");

 for (i=0;i<1000;i++)
 {
  fflush(stdin);

  gets (temp);

  if (strlen(temp) != 0)
  {
   name[i] = (char *) malloc (strlen(temp)+1);
   strcpy (name[i],temp);
  }
  else
   break;
 }

 printf ("\n\nNames that you have entered are: ");

 for (k=0;k<i;k++)
 {
  printf ("\n%s",name[k]);
 }

 printf ("\n\npress any key to close.");
 getch();
}

Sample Output

dynamic memory allocating using malloc function

No comments :

Post a Comment

Note: Only a member of this blog may post a comment.

Copyright 2017. All Rights Reserved. Privacy Policy / Terms And Conditions / Sitemap / Contact