Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Explain the pointers to unions in C language
A union in C is a memory location that is shared by several variables of different data types. A pointer to union is a variable that stores the address of a union, allowing us to access union members using the arrow operator (->) just like with structures.
Syntax
union uniontag {
datatype member1;
datatype member2;
/* ... */
datatype membern;
};
union uniontag *ptr; // Pointer to union
Declaration of Union and Pointer
There are different ways to declare unions and their pointers −
Method 1: Declare union type and variable separately
union sample {
int a;
float b;
char c;
};
union sample s; // Union variable
union sample *ptr; // Pointer to union
Method 2: Declare union and variable together
union sample {
int a;
float b;
char c;
} s, *ptr; // Variable and pointer declared together
Example 1: Basic Pointer to Union
The following example demonstrates how to use pointers to access union members −
#include <stdio.h>
union data {
int num;
char ch;
};
int main() {
union data d1;
union data *ptr = &d1; // Pointer to union
// Accessing through pointer using arrow operator
ptr->num = 75;
printf("Integer value: %d
", ptr->num);
printf("Character value: %c
", ptr->ch);
return 0;
}
Integer value: 75 Character value: K
Example 2: Dynamic Memory Allocation for Union
This example shows how to dynamically allocate memory for a union using pointers −
#include <stdio.h>
#include <stdlib.h>
union number {
int intVal;
float floatVal;
};
int main() {
union number *ptr;
// Allocate memory for union
ptr = (union number*)malloc(sizeof(union number));
if (ptr == NULL) {
printf("Memory allocation failed
");
return 1;
}
// Store integer value
ptr->intVal = 100;
printf("Integer: %d
", ptr->intVal);
// Store float value (overwrites integer)
ptr->floatVal = 45.67f;
printf("Float: %.2f
", ptr->floatVal);
printf("Integer after float assignment: %d
", ptr->intVal);
free(ptr); // Free allocated memory
return 0;
}
Integer: 100 Float: 45.67 Integer after float assignment: 1110179840
Key Points
- Union members share the same memory location, so only one member can hold a valid value at a time
- The arrow operator (->) is used to access union members through pointers
- The dot operator (.) is used for direct union variable access
- Memory size of a union equals the size of its largest member
- Always free dynamically allocated memory to prevent memory leaks
Conclusion
Pointers to unions in C provide an efficient way to access union members using the arrow operator. They are particularly useful for dynamic memory allocation and when passing unions to functions, offering flexibility in handling different data types within the same memory location.
