Horje
How to Declare a Pointer to a Union in C?

Union is a user-defined data type in C language that can contain elements of the different data types and pointers are used to store memory addresses. In this article, we will learn how to declare a pointer to a union in C++.

Pointer to Union in C

To declare a pointer to a union first, define a union and then declare a pointer that points to the union type using the below syntax:

Syntax to Declare Pointer to Union in C

//Define Union
union unionName {
int var1;
float var2;
};

//declare pointer to union
union unionName *ptr;

We can also assign the pointer the address of some union variable by using the addressof(&) operator.

C Program to Declare Pointer to Union

The following programs show how to declare pointers to unions in C programming and access members using the arrow operator (->).

C

// C program to declare pointer to union
#include <stdio.h>
  
// Defining a union
union myUnion {
    int intValue;
    float floatValue;
    char charValue;
};
  
int main()
{
    // Creating a union variable
    union myUnion u;
  
    // Declaring a pointer to the union and assign it the
    // address of the union variable
    union myUnion* ptr = &u;
  
    // Using the pointer to Set the intValue member of the
    // union
    ptr->intValue = 100;
  
    // Accessing the intValue member of the union
    printf("The intValue is: %d\n", ptr->intValue);
  
    // set value for floatValue This will overwrite the
    // intValue
    ptr->floatValue = 3.14;
  
    // Accessing the floatValue member of the union
    printf("The floatValue is: %f\n", ptr->floatValue);
  
    return 0;
}

Output

The intValue is: 100
The floatValue is: 3.140000



Reffered: https://www.geeksforgeeks.org


C Language

Related
How to Delete an Element from an Array of Structs in C? How to Delete an Element from an Array of Structs in C?
How to Use a Union to Save Memory in C? How to Use a Union to Save Memory in C?
How to Declare a Struct Inside a Struct in C? How to Declare a Struct Inside a Struct in C?
How to Initialize Char Array in Struct in C? How to Initialize Char Array in Struct in C?
How to Modify Struct Members Using a Pointer in C? How to Modify Struct Members Using a Pointer in C?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
12