Pointer to structure
A pointer to a structure can be used by the '&' operator.Take the struct student and define the s1 variable of type struct student
struct student s1;
&s1 will give the starting address of the structure.
The variable and the pointer variable can be combined and declared as follows:
struct student
{
.
.
}
s1, *ptr_stud;
ptr_stud = &s1;
Accessing members of structure which has a pointer is
ptvar → member
Where,
ptvar is a structure type pointer variable
→ is comparable to the '.' operator.
The '.' operator requires a structure variable whereas a → requires a structure pointer on its left side.
Following table will tell us how the members of structures are accessed by using the structure pointer:
| Member | Structure variable | Structure pointer |
|---|---|---|
| Ordinary variable | var.member s1.roll_no | ptvar → member (ptr_stud → roll_no) (*ptr_stud). roll_no |
| Array | var.member[expression] s1. name | ptvar → member[expression] ptr_stud → name (*ptr_emp).name |
| Nested structure | var.member.submember s1.n.last_name | ptrvar → member.submember ptr_stud → n.last_name (*ptr_stud).n.last_name |
Passing the structures as parameters
A structure can be passed as a parameter to a function. This can be done by using three methods.1. Individual structure members
As the members of the structures are individual entities they can be passed and returned from the functions.
Example : The coordinates of a point is returned
#include <stdio.h>
typedef struct
{
int a;
int b;
}point;
void d(int, int);
void main()
{
point p1 = {5,10};
d(p1.a, p1.b);
}
void d(int x, int y)
{
printf("The coordinates are : %d %d",x,y);
}
Output:
The coordinates are : 5 10
2. Passing structure as a whole
An entire structure can be passed as an argument. It is passed by using the call by value method.
Syntax:
struct struct_name func_name (struct struct_name struct_var);
Note: The above syntax can vary as per the needs.
Example : Passing a structure to a function by using the call by value method
#include <stdio.h>
typedef struct
{
int a;
int b;
}point;
void d(point);
void main()
{
point p1 = {15,20};
d(p1);
}
void d(point p)
{
printf("%d %d",p.a,p.b);
}
Output:
15 20
3. Passing pointer to structure
- When large structures are required for passing a function using the call by value method is inefficient. Instead it can be done by using pointers.
- It is common for creating a pointer to structure.
- A pointer to a structure is not a structure itself but a variable which holds the address of the structure.
Syntax
struct struct_name
{
member 1;
member 2;
.
.
member n;
}*ptr;
OR
struct struct_name *ptr;
Example:
struct student *ptr_stud, stud;
After this we need to assign an address of the stud to the pointer.
Hence, we will write
ptr_stud = &stud;
For accessing the members we will write
(*ptr_stud).fees
The above statement can also be written in the following format:
ptr_stud → fees = 50000;
It is more easier to work with this statement.


