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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.