C accessing union members



We have already seen tutorial which provides the basics of union in c programming. In this tutorial we are learning the way for accessing union members in C Programming.

C Programming Accessing union members

While accessing union, we can have access to single data member at a time. we can access single union member using following two Operators –

  1. Using DOT Operator
  2. Using ARROW Operator

Accessing union members DOT operator

In order to access the member of the union we are using the dot operator. DOT operator is used inside printf and scanf statement to get/set value from/of union member location.

Syntax :

variable_name.member

consider the below union, when we declare a variable of union type then we will be accessing union members using dot operator.

union emp
{
int id;
char name[20];
}e1;

id can be Accessed by – union_variable.member

Syntax Explanation
e1.id Access id field of union
e1.name Access name field of union

Accessing union members Arrow operator

Instead of maintaing the union variable suppose we store union at particular address then we can access the members of the union using pointer to the union and arrow operator.

union emp
{
int id;
char name[20];
}*e1;

id can be Accessed by – union_variable->member

Syntax Explanation
e1->id Access id field of union
e1->name Access name field of union

C Programs

Program #1 : Using dot operator

#include <stdio.h>

union emp
{
  int id;
  char name[20];
}e1;


int main(int argc, char *argv[])
{
    e1.id = 10;
    printf("\nID   : %d",e1.id);

    strcpy(e1.name,"Pritesh");
    printf("\nName : %s",e1.name);
	
    return 0;
}

Output :

ID   : 10
Name : Pritesh

Program #2 : Accessing same memory

#include <stdio.h>

union emp
{
  int id;
  char name[20];
}e1;


int main(int argc, char *argv[])
{
    e1.id = 10;
    strcpy(e1.name,"Pritesh");

    printf("\nID   : %d",e1.id);
    printf("\nName : %s",e1.name);
	
    return 0;
}

Output :

ID   : 1953067600
Name : Pritesh

As we already discussed in the previous article of union basics, we have seen how memory is shared by all union fields. In the above example –

Total memory for union = max(sizeof(id),sizeof(name)) 
                       = sizeof(name)
                       = 20 bytes 

Firstly we have utilized first two bytes out of 20 bytes for storing integer value. After execution of statement again same memory is overridden by character array so while printing the ID value, garbage value gets printed

Program #3 : Using arrow operator

#include <stdio.h>

union emp
{
  int id;
  char name[20];
}*e1;


int main(int argc, char *argv[])
{
    e1->id = 10;
    printf("\nID   : %d",e1->id);

    strcpy(e1->name,"Pritesh");
    printf("\nName : %s",e1->name);
	
    return 0;
}

Output :

ID   : 10
Name : Pritesh