Study of dynamic memory allocation. A program to store the names of five persons and search for a person.

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

#define SIZE 5

int getName(char *);

int main(void)
{
int i, cnt;
char *names[SIZE], tmp[50];

for(i = 0 ; i < SIZE ; i++)
{
names[i] = (char *) malloc(getName(tmp) + 1);
if(names[i] == NULL)
{
printf("\nMemory allocation for name %d failed.", i + 1);
return 1;
}
strcpy(names[i], tmp);
}

printf("\nEnter name to search : ");
gets(tmp);

for(i = 0 ; i < SIZE ; i++)
{
if(strcmp(names[i], tmp) == 0)
{
printf("\nName found at position number %d", i + 1);
break;
}
}

if(i == SIZE) printf("\nName NOT found");

for(i = 0 ; i < SIZE ; i++)
free(names[i]);

return 0;
}

int getName(char *s)
{
printf("\nName : ");
gets(s);
return strlen(s);
}

No comments:

Post a Comment

kiss on google ads if you are anonymous because your ip is trackable.thank you.

......from.admin