Structure and Pointer

As we have already study how to define pointer to a datatype like int, char, float etc. In same way we can define a pointer to a structure like given below:

struct sitedetail{

char full_name[50];

int num_of_member;

};

struct sitedetail *gyan;

Accessing pointer to structure members

Let’s illustrate how ‘ -> ‘ arrow operator is used to access member of  pointer to structure variable, see an example.

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

struct site_detail{

        char full_name[50];

        int num_of_member;

        };

int main()

{

        struct site_detail *gyan;

        gyan = (struct site_detail*)malloc(sizeof(struct site_detail));

        printf(“Enter website name and member of website\n”);

        gets(gyan->full_name);

        scanf(“%d”,&gyan->num_of_member);

        printf(“Website name = %s\nNum of member = %d\n”,gyan->full_name, gyan->num_of_member);

        return 0;

}

Output:

$ ./a.exe

Enter website name and member of website

gyantoday.com

10000

Website name = gyantoday.com

Num of member = 10000

 

Pointer variable as a member of structure

Also a structure can have one or multiple pointer variable member, see an example below.

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

struct site_detail{

        char *full_name;

        int num_of_member;

        };

int main()

{

        struct site_detail *gyan;

        gyan = (struct site_detail*)malloc(sizeof(struct site_detail));

        gyan->full_name = (char *)malloc(50 * sizeof(char));

        printf(“Enter website name and member of website\n”);

        gets(gyan->full_name);

        scanf(“%d”,&gyan->num_of_member);

        printf(“Website name = %s\nNum of member = %d\n”,gyan->full_name, gyan->num_of_member);

        return 0;

}

Output:

$ ./a.exe

Enter website name and member of website

gyantoday.com

10000

Website name = gyantoday.com

Num of member = 10000

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.