What are pointers to structures in C language?


Pointer to structure holds the add of the entire structure.

It is used to create complex data structures such as linked lists, trees, graphs, and so on.

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

Declaration

Following is the declaration for pointers to structures in C programming

struct tagname *ptr;

For example − struct student *s −

Accessing

It is explained below how to access the pointers to structures.

Ptr-> membername;

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

Example Program

The following program shows the usage of pointers to structures −

#include<stdio.h>
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");
   printf ("Number = %d
"
, st ->sno);    printf ("name = %s
"
, st->sname);    printf ("marks =%f
"
, st ->marks);    getch ( ); }

Output

Let us run the above program that will produce the following result −

enter sno, sname, marks:1 Lucky 98
details of the student are:
Number = 1
name = Lucky
marks =98.000000

Example 2

Consider another example which explains the functioning of pointers to structures.

 Live Demo

#include<stdio.h>
struct person{
   int age;
   float weight;
};
int main(){
   struct person *personPtr, person1;
   personPtr = &person1;
   printf("Enter age: ");
   scanf("%d", &personPtr->age);
   printf("Enter weight: ");
   scanf("%f", &personPtr->weight);
   printf("Displaying:
"
);    printf("Age: %d
"
, personPtr->age);    printf("weight: %f", personPtr->weight);    return 0; }

Output

Let us run the above program that will produce the following result −

Enter age: 45
Enter weight: 60
Displaying:
Age: 45
weight: 60.000000

Updated on: 14-Sep-2023

25K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements