In this tutorial, you will learn how to use pointers in structure and how to access the members of structure using pointer. But before, if you do not know about structure and pointers click the link below.
Use of pointer in Structure in C
We use pointers in structure to define a pointer variable of the struct. Just like we define the pointer with any other variable, a pointer is also defined with struct in the same way.
1 2 3 4 5 6 7 8 9 10 11 12 13 | struct struct_name { data_type member1; data_type member2; ... ... }; int main() { //defining the structure pointer variable struct struct_name *struct_pointer; } |
Now struct_pointer points to the structure. And we can store the address of the structure variables in that pointer.
Accessing Structure members using pointer.
As discussed earlier in Structure, there are two ways to access the members of the structure. One is dot operator(.
) (already discussed), another is ->
operator.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | #include <stdio.h> struct student { char name[25]; int roll_no; }; int main() { struct student *studentPtr, s1; studentPtr = &s1; printf("Enter the Name: "); scanf("%[^\n]s", &studentPtr->name); printf("Enter the Roll Number: "); scanf("%d", &studentPtr->roll_no); //Displaying printf("\nName of the student: %s\n", studentPtr->name); printf("Roll of the Student: %d", studentPtr->roll_no); return 0; } |
Output:
1 2 3 4 5 | Enter the Name: James Shatt Enter the Roll Number: 101 Name of the student: James Shatt Roll of the Student: 101 |