by Dinesh Thakur Category: Structure And Union

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;




    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)



            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);


         C Program to read and print info of a person

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.