![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Explain the Union to pointer in C language
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 −
#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
Advertisements