The ones who are crazy enough to think they can change the world are the ones who do.- Steve Jobs
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.
struct structname { data type member1; data type member2; }variable1, *ptrvariable1; //Pointer to structure declaration
A structure member can be accessed using its corresponding pointer variable. To access structure members, the (.)dot operator is used with the pointer variable.
(*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,
*ptrvariable −> member1;
The "−>" can be combined with (.)dot (or) period operator to access a structure members.
Lets code pointers to structure and have some fun
#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; }
The above program illustrates that the structure members are accessed through pointer variable studptr.
We may make mistakes(spelling, program bug, typing mistake and etc.), So we have this container to collect mistakes. We highly respect your findings.
© Copyright 2019