The ones who are crazy enough to think they can change the world are the ones who do.
- Steve Jobs

Pointer to Structure

In C, the pointer is a variable that holds the address of another data variable. A pointer to structure means a pointer variable can hold the address of a structure. The address of structure variable can be obtained by using the '&' operator. All structure members inside the structure can be accessed using pointer, by assigning the structure variable address to the pointer. The pointer variable occupies 4 bytes of memory in 32-bit machine and 8 bytes in 64-bit machine.

Syntax - Pointer to Structure

Syntax
struct structname {
data type member1;
data type member2;
}variable1, *ptrvariable1;     //Pointer to structure declaration

Accessing Structure Members Using Pointers

A structure member can be accessed using its corresponding pointer variable. To access structure members, the (.)dot operator is used with the pointer variable.

Syntax-1
(*ptrvariable).member1;

The (•)dot operator has a higher precedence than operator ' * '. The alternative to (•)dot operator is −> operator. Now it can also be written as,

Syntax-1
*ptrvariable −> member1;

The "−>" can be combined with (.)dot (or) period operator to access a structure members.

C program - Pointers to Structure

Lets code pointers to structure and have some fun

pointer-struct-1.c
#include <stdio.h>
int main()
{
//Structure Declaration
struct student{
char name[40];
struct avg{
int sub1, sub2, sub3;
float average;
}avg;
}stud1, *studptr = &stud1;  //Pointer variable stores the address of structure variable
int total;
printf("Enter the Name of the student : ");
scanf("%s", (*studptr).name);
printf("\n------Enter the marks of the student------ ");
printf("\nEnter sub1 marks : ");
scanf("%d",&studptr->avg.sub1);
printf("\nEnter sub2 marks : ");
scanf("%d",&studptr->avg.sub2);
printf("\nEnter sub3 marks : ");
scanf("%d",&studptr->avg.sub3);
total = (studptr->avg.sub1 + studptr->avg.sub2 + studptr->avg.sub3);
studptr->avg.average = total / 3;
printf("\n-------Student Details-------\n ");
printf("Name: %s", studptr->name);
printf("\nsub1: %d ", studptr->avg.sub1);
printf("\nsub2: %d ", studptr->avg.sub2);
printf("\nsub3: %d ", studptr->avg.sub3);
printf("\nAverage: %f ", studptr->avg.average);
return 0;
}
  • Enter the Name of the student :siva
  • ------Enter the marks of the student------
  • Enter sub1 marks :78
  • Enter sub2 marks :82
  • Enter sub3 marks :80
  • -------Student Details-------
  • Name: siva
  • sub1: 78
  • sub2: 82
  • sub3: 80
  • Average:80.000000

Note:

The above program illustrates that the structure members are accessed through pointer variable studptr.

Report Us

We may make mistakes(spelling, program bug, typing mistake and etc.), So we have this container to collect mistakes. We highly respect your findings.

Report