Home >Backend Development >C++ >Explain union pointers in C language

Explain union pointers in C language

王林
王林forward
2023-09-12 13:45:04646browse

Explain union pointers in C language

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

Syntax

The syntax of pointer to union 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 structures.

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

Declaration of joint variables

The following is the declaration of joint variables. It has three types as follows −

Type 1

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

The translation of Type 2

is:

Type 2

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

Type 3

The translation is:

Type 3

union sample{
   int a;
   float b;
   char c;
};
union sample s;
  • When declaring a union, the compiler will automatically create the largest size variable type to accommodate the variables in the union.

  • Only one variable can be referenced at any time.

  • Use the same structure syntax to access union members.

  • The dot operator is used to access members.

  • The arrow operator (->) is used to access members using pointers.

We can use pointers to unions and use the arrow operator (->) to access members, just like a structure.

Example

The following program shows the usage of pointers to unions 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 results −

75 K

Example 2

Consider the same example with different inputs.

Real-time demonstration

#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 results −

90 Z

The above is the detailed content of Explain union pointers in C language. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete