Horje
How to Declare a Struct Member Inside a Union in C?

A union contains different types of variables as its members and all these members share a memory location. In this article, we will learn how to declare and access the struct member inside a union in C++.

Structure Inside Union in C

To declare a structure inside a union we can use the below syntax:

Syntax to Declare Structure Inside Union in C

union unionName {
    struct structName structVar; // Struct as a member of the union
};

Here, structName is the name of the structure defined somewhere before the union declaration.

We can also declare the structure member directly inside the union as shown:

union unionName {
struct structName {
struct_member1;
struct_member2;
}structVar; // Struct as a member of the union
};

C Program to Declare Structure Inside Union

The below program demonstrates how we can declare a structure inside a union in C.

C

// C Program to declare struct inside union
  
#include <stdio.h>
  
// Define a struct
struct Point {
    int x;
    int y;
};
  
// Define a union with a struct as a member
union Data {
    int num;
    char ch;
    struct Point point; // Struct inside the union
};
  
int main()
{
    // Declare and initialize a union variable
    union Data data;
  
    // Access and modify members of the union
    data.num = 42;
    printf("Number: %d\n", data.num);
  
    data.ch = 'A';
    printf("Character: %c\n", data.ch);
  
    data.point.x = 10;
    data.point.y = 20;
  
    // print the data
    printf("Point: (%d, %d)\n", data.point.x, data.point.y);
  
    return 0;
}

Output

Number: 42
Character: A
Point: (10, 20)





Reffered: https://www.geeksforgeeks.org


C Language

Related
How to Use bsearch with an Array in C? How to Use bsearch with an Array in C?
How to Initialize a 2D Array in C? How to Initialize a 2D Array in C?
How to Declare a Pointer to a Union in C? How to Declare a Pointer to a Union in C?
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?

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