Pointer to Structure

 

Pointer to Structure: A pointer is a variable which hold the starting address of another variable, it may be of type integer, float and character. Similarly, if the variable is of structure type there for accessing the starting address of structure, we must declare pointer for a structure variable. This pointer is also called as structure to pointer.

Pointer to structure  can be declared as follow:

Syntax:

struct <structure_name>

{

//structure elements/Members ;

} ;

struct <structure_name> <structure_variable>,* <pointer_variable_name>;

 

For example:

struct student     // here student is name of student 

{

int rollno;     // Structure members 

             char sname[50];

             char sclass[20];

             char city[30];

             float marks;

};

struct student s,*ptr;    // here ptr is declaring as pointer

 ptr=&s;          //initialized pointer to structure variable

Here, ptr is a pointer variable, which points to the structure s.ptr can hold the starting address of the structure variable rollno.

            There are two ways for accessing the member of structure through the structure pointer. First is to use the arrow operator (->)-

<pointer variable > -> <structure variable name>;

For example:   ptr->rollno;

Other way for accessing member elements as –

Syntax:

            (*<pointer_variable_name><struct_variable_name>;

For example: (*ptr.rollno);

For Example: Write a program to demonstrate the use of pointer to structure

#include<stdio.h>

#include<conio.h>

struct student    // Student is name of structure 

{

int rollno;  // structure members/elements

char sname[50];

char sclass[20];

char city[30];

float marks;

};

void main()

{

struct student s,*ptr;    //structure declaring as pointer

             ptr=&s;          //initialized pointer to structure variable

             printf("\n Enter Roll Number of Student: ");

             scanf("%d",&s.rollno);

             printf("\n Enter name of student: ");

             scanf("%s",&s.sname);

             printf("\n Enter city: ");

             scanf("%s",&s.city);

             printf("Enter student marks: ");

             scanf("%f",&s.marks);

             printf("\n -------------------------------");

             printf("\n -----Students Details------");

             printf("\n ------------------------------");

             printf("\n Roll is: %d",(*ptr).rollno);

             printf("\n Name is: %s",(*ptr).sname);

             printf("\n City is: %s",(*ptr).city);

             printf("\n Marks: %f ",(*ptr).marks);

              getch();

}

Output: 



Comments

Popular posts from this blog

Write a program in Program Notebook......