A union is a memory location shared by multiple variables of different data types.
The syntax of pointer to union in C programming is as follows -
union uniontag{ datatype member 1; datatype member 2; ---- ---- datatype member n; };
The following example shows the usage of union of structures.
union sample{ int a; float b; char c; };
The following is the declaration of joint variables. It has three types as follows −
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 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.
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; }
When the above program is executed, it produces the following results −
75 K
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; }
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!