Explain the Union to pointer in C language

CServer Side ProgrammingProgramming

A union is called as a memory location, which is shared by several variables of different data types.

Syntax

The syntax is as follows −

union uniontag{
   datatype member 1;
   datatype member 2;
   ----
   ----
   datatype member n;
};

For example,

union sample{
   int a;
   float b;
   char c;
};

Declaration of union variable

Given below are the respective declarations of union variable −

Union sample

{
   int a;
   float b;
   char c;
}s;

Union

{
   int a;
   float b;
   char c;
}s;

Union sample

{
   int a;
   float b;
   char c;
};
union sample s;

When union is declared, the compiler automatically creates a variable which hold the largest variable type in the union.

At any time, only one variable can be referred.

Initialization and accessing

  • Accessing union member is same as the structure.
  • Generally, the dot operator is used for accessing members.
  • The arrow operator ( ->) is used for accessing the members
  • There is no restriction while using data type in a union.

Example

Following is the C program for union to pointer −

 Live Demo

#include<stdio.h>
union abc{
   int a;
   char b;
};
int main(){
   union abc var;
   var.a=90;
   union abc *p=&var;
   printf("%d%c",p->a,p->b);
}

Output

When the above program is executed, it produces the following result −

90Z
raja
Published on 09-Mar-2021 09:33:27
Advertisements