Structure with Pointers

The C language allows to define a pointer to structure, where the pointer variable can point to the address of a structure variable. This is done in the same way as a pointer declared to any datatype. The syntax of defining a structure pointer is as follows :
 struct structure_name *pointer_name;
Now lets see how we can declare a pointer to a  structure variable, take a look at the below code :
struct Student {
  char name[20];
  int age;
  char gender[5]; 
}

struct Student s1;
At above code there is a structure called Student and and a structure variable is declared called s1. Now the below statement will create a pointer to the structure Student;
 struct Student *ptr;
This declares a pointer ptr that can store the address of the variable of type struct Student. We can now assign the address of structure variable s1 to ptr using & operator.
 ptr = &s1;
Now ptr points to the structure variable s1.

Accessing the structure members using pointer:

There are two ways of accessing structure members of structure using pointer:

1. By using indirection operator ( * ) :

The structure members can be accessed by using indirection operator (*), in conjunction with the normal Dot (.) operator which is used within normal structure variable. For example :
 (*ptr).name
 (*ptr).age
 (*ptr).gender
Parentheses around *ptr are necessary because the precedence of dot(.) operator is greater than that of indirection (*) operator. Now lets see a C example code.
#include <stdio.h>
#include <string.h>

struct Student {
  char name[20];
  int age;
  char gender[10];
};

int main() {
  struct Student s1;
  struct Student *ptr;
  ptr = &s1;

  strncpy((*ptr).name, "Sanjay Kumar", 20);
  (*ptr).age = 25;
  strncpy((*ptr).gender,"Male",10);

  printf("Student Name : %s\n", (*ptr).name);
  printf("Student Age : %d\n", (*ptr).age);
  printf("Student Gender : %s\n", (*ptr).gender);

  return 0;
}
Output :

Student Name : Sanjay Kumar
Student Age : 25
Student Gender : Male

2. By using Arrow operator ( -> ) :

In this method of accessing the structure variables we don't have to use the asterisk (*) or bracket with the pointer variable, instead we only have to use the arrow operator ( -> ) write after pointer variable followed by the name of structure member. For example :
 ptr->name
 ptr->age
 ptr->gender
C example code :
#include <stdio.h>
#include <string.h>

struct Student {
  char name[20];
  int age;
  char gender[10];
};

int main() {
  struct Student s1;
  struct Student *ptr;
  ptr = &s1;
  strncpy(ptr->name, "Priya Shyam", 20);
  ptr->age = 22;
  strncpy(ptr->gender,"Female",10);

  printf("Student Name : %s\n", ptr->name);  
  printf("Student Age : %d\n", ptr->age);
  printf("Student Gender : %s\n", ptr->gender);

  return 0;
}
Output :

Student Name : Priya Shyam
Student Age : 22
Student Gender : Female


Next Topic :