Explain the pointers to unions in C language



A union is a memory location that is shared by several variables of different data types.

Syntax

The syntax for the pointers to unions in C programming is as follows −

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

Example

The following example shows the usage of union of structure.

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

Declaration of union variable

Following is the declaration for union variable. It is of three types as follows −

Type 1

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

Type 2

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

Type 3

union sample{    int a;    float b;    char c; }; union sample s;
  • When union is declared, the compiler automatically creates largest size variable type to hold variables in the union.

  • At any time only one variable can be referred.

  • Same syntax of structure is used to access a union member.

  • The dot operator is for accessing members.

  • The arrow operator ( ->) is used for accessing the members using pointer.

We have pointers to unions and can access members using the arrow operator (->) just like structures.

Example

The following program shows the usage of pointers to union in C programming −

 Live Demo

#include <stdio.h> union pointer {    int num;    char a; }; int main(){    union pointer p1;    p1.num = 75;    // p2 is a pointer to union p1    union pointer* p2 = &p1;    // Accessing union members using pointer    printf("%d %c", p2->num, p2->a);    return 0; }

Output

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

75 K

Example 2

Consider the same example with different input.

 Live Demo

#include <stdio.h> union pointer {    int num;    char a; }; int main(){    union pointer p1;    p1.num = 90;    // p2 is a pointer to union p1    union pointer* p2 = &p1;    // Accessing union members using pointer    printf("%d %c", p2->num, p2->a);    return 0; }

Output

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

90 Z
Updated on: 2021-03-24T14:03:36+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements