C pointer to union



Previously we have learnt about basics of union in c programming and way to access a member of union.

In this tutorial we will be learning about pointer to union i.e pointer which is capable of storing the address of an union in c programming.

C programming pointer to union

We know that pointer is special kind of variable which is capable of storing the address of a variable 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 –

  1. Step 1 : We have declared a variable of type union.
  2. Step 2 : Now declare a pointer to union
  3. Step 3 : Uninitialized pointer is of no use so need to initialize it

Recommended Article : See some common mistakes of a pointer

Program

#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

  1. sptr is pointer to union address.
  2. -> and (*).  both represents the same.
  3. 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