How to access the pointer to structure in C language?

CServer Side ProgrammingProgramming

Pointer to structure holds the address of an entire structure.

Mainly, these are used to create the complex data structures such as linked lists, trees, graphs and so on.

The members of the structure can be accessed by using a special operator called arrow operator ( -> ).

Declaration

Following is the declaration for pointer to structure −

struct tagname *ptr;

For example, struct student *s;

Accessing

You can access pointer to structure by using the following −

Ptr-> membername;

For example, s->sno, s->sname, s->marks;

Example

Following is the C program to access the pointer to structure −

#include<stdio.h>
struct classroom{
   int students[7];
};
int main(){
   struct classroom clr = {2, 3, 5, 7, 11, 13};
   int *ptr;
   ptr = (int *)&clr;
   printf("%d",*(ptr + 4));
   return 0;
}

Output

When the above program is executed, it produces the following result −

11

Explanation

Here, a pointer variable ptr holds the address of a first value 2 of an object clr. Then, the address of the pointer variable is incremented by 4 and finally, the value is displayed.

For example,

*(ptr + 0) = 2
*(ptr + 1) = 3
*(ptr + 2) = 5
*(ptr + 3) = 7
*(ptr + 4) = 11
*(ptr + 5) = 13

Consider another simple example to know about pointer to structures −

Example

struct student{
   int sno;
   char sname[30];
   float marks;
};
main ( ){
   struct student s;
   struct student *st;
   printf("enter sno, sname, marks :");
   scanf ("%d%s%f", & s.sno, s.sname, &s. marks);
   st = &s;
   printf ("details of the student are\n");
   printf ("Number = %d\n", st ->sno);
   printf ("name = %s\n", st->sname);
   printf ("marks =%f", st->marks);
   getch ( );
}

Output

When the above program is executed, it produces the following result −

enter sno, sname, marks :1 bhanu 69
details of the student are
Number = 1
name = bhanu
marks =69.000000
raja
Published on 09-Mar-2021 08:08:31
Advertisements