The program given below reads the information about a person and prints it on the screen. It uses a structure containing a pointer member name to represent the information about a person. Note that the program uses the dstr_read function.
/* Program to read and print info of a person. Uses a structure with char pointer to store person’s name */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct person {
char *name; /*person’s name */
char gender; /* M: male, F: female */
int age;
} ;
char *dstr_read();
void person_read(struct person *p);
void person_print(struct person *p);
int main()
{
struct person p;
person_read(&p);
person_print(&p);
free(p.name);
return 0;
}
/* read a dynamically allocated string */
char *dstr_read()
{
char buf[100];
char *str;
gets (buf); /* read a string in buffer */
/* allocate required memory */
str = (char*) malloc(strlen(buf) + 1);
if (str == NULL) {
printf(“Error: Out of memory …\n”);
exit (1);
}
return strcpy(str, buf); /*copy string and retrun ptr */
}
/* read a person’s info */
void person_read(struct person *p)
{
clrscr();
printf(“Enter person’s information:\n”);
printf(“Name: “);
p->name = dstr_read();
printf(“Gender (M/F): “);
scanf(” %c”, &p->gender);
printf(“Age : “);
scanf(“%d”, &p->age);
}
/* print a person’s info */
void person_print(struct person *p)
{
printf(“Name : %s\n”, p->name);
printf (“Gender : %s\n”, p->gender == ‘M’ ? “Male” : “Female”);
printf (“Age : %d\n”, p->age);
}