-->

Pointer to structure

Pointer to structure
Pointer to structure
·         Pointer which stores the address of a structure is called as "pointer to structure".
·         C language can define a pointer variable of structure type. The pointer variable to structure variable is declared by using same syntax to define a pointer variable of data type.
The syntax to define the pointer to structure
struct <struct_name> *<pointer_var_name>;
Example:
struct employee *emp;
It declares a pointer variable "emp" of employee type.
Example:
struct book
{
char name[20];
float price;
long iso;
} b.*p;
'p' is a pointer variable to the variables of type struct book.
main()
{
b={ "let us c", 200, 1234567};
printf("%s %f %d", b.name, b.price, b.iso);
printf("%s %f %d", p à name, p à price, p à iso);
}

Difference between dot and arrow operator:
If we want to access the members of a structure with the help of structure variables then dot (.) operator will be used.
If you want to access the members of a structure with the help of a pointer to that structure then arrow (à) operator will be used.
Example:
'p —> name' is same as 'b.name'

Self referential and Complex structure
Self-referential structures:
Self-referential structures contain a pointer member that points to a structure of the same structure type.
Example:
struct node
{
int data;
struct node *nextPtr;
} 
·         is a pointer member that points to a structure of the same type as the one being declared.
·         is referred to as a link. Links can tie one node to another node.
Self-referential structures can be linked together to form useful data structures such as lists, queues, stacks and trees.

Complex structure:
If a structure contains at least an array or a structure, it is called a complex structure. The structure that contains only scalar variables is called simple structure.
We can define a complex structure called customer that contains address structure as follows:
struct customer
{
char name[50];
structure address billing_addr;

structure address shipping_addr;
};

Related Posts

Subscribe Our Newsletter