Pointer to Union in C language

C language | Pointer to Union: Here, we are going to learn about creating union pointer, changing, and accessing union members using the pointer.
Submitted by IncludeHelp, on June 25, 2020

Pointer to Union

Pointer to union can be created just like other pointers to primitive data types.

Consider the below union declaration:

union number{
    int a;
    int b;
};

Here, a and b are the members of the union number.

Union variable declaration:

union number n;

Here, n is the variable to number.

Pointer to union declaration and initialization:

union number *ptr = &n;

Here, ptr is the pointer to the union and it is assigning with the address of the union variable n.

Accessing union member using union to pointer:

Syntax:
pointer_name->member;

Example:
// to access members a and b using ptr
ptr->a;
ptr->b;

C program to demonstrate example of union to pointer

#include <stdio.h>

int main()
{
    // union declaration
    union number {
        int a;
        int b;
    };

    // union variable declaration
    union number n = { 10 }; // a will be assigned with 10

    // pointer to union
    union number* ptr = &n;

    printf("a = %d\n", ptr->a);

    // changing the value of a
    ptr->a = 20;
    printf("a = %d\n", ptr->a);

    // changing the value of b
    ptr->b = 30;
    printf("b = %d\n", ptr->b);

    return 0;
}

Output:

a = 10
a = 20
b = 30

Related Tutorials



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.