Here we will be learning about pointer to union i.e pointer which is capable of storing the address of an union in c programming.
Pointer to union:
Pointer which stores address of union is called as pointer to union
Syntax
union team t1; //Declaring union variable
union team *sptr; //Declaring union pointer variable
sptr = &t1; //Assigning address to union pointer
In the above syntax that we have shown –
Step 1 : We have declared a variable of type union.
Step 2 : Now declare a pointer to union
Step 3 : Uninitialized pointer is of no use so need to initialize it
#include<stdio.h>
union team {
char *name;
int members;
char captain[20];
};
int main()
{
union team t1,*sptr = &t1;
t1.name = "India";
printf("\nTeam : %s",(*sptr).name);
printf("\nTeam : %s",sptr->name);
return 0;
}
Output :
Team = India
Team = India
Program explanation
sptr is pointer to union address.
-> and (*). both represents the same.
These operators are used to access data member of structure by using union’s pointer.
Summary
In order to access the members of union using pointer we can use following syntax –
Code Explanation
(*sptr).name Used for accessing name
sptr->name Used for accessing name