POINTERS IN STRUCTURES
A struct in the C programming language is a composite data type declaration that defines a physically grouped list of variables under one name in a block of memory, allowing the different variables to be accessed via a single pointer or by the struct declared name which returns the same address.
A pointer is a variable that points to the address of another variable of any data type like int, char, float, etc. Similarly, we can have a pointer to structures, where a pointer variable can point to the address of a structure variable.
We can declare a pointer to a structure variable in below way
struct dog{char name[10];char breed[10];int age;char colour[10];};struct dog spike;struct dog *ptr_dog
This declares a pointer ptr_dog that can store the address of the variable of type struct dog. We can now assign the address of variable spike to ptr_dog using & operator.
ptr_dog=&spike;
Now ptr_dog points to the structure variable spike.
ACCESSING MEMBERS USING POINTER
There are two ways of accessing members of structure using pointer:
- Using indirection (*) operator and dot (.) operator.
- Using arrow (->) operator or membership operator.
Indirection (*) operator and dot (.) operator- To access a member of structure write *ptr_dog followed by a dot(.) operator, followed by the name of the member. For example:- (*ptr_dog).name - refers to the name of dog.
(*ptr_dog).breed - refers to the breed of dog.
Arrow (->) operator- To access members using arrow (->) operator write pointer variable followed by -> operator, followed by name of the member. Here we don't need parentheses, asterisk (*) and dot (.) operator. This method is much more readable and intuitive.
0 Comments
Doubts? Please let our team know So that we can serve you better.