Pointer to union

C program to show the usage of pointer to union.


Program

#include<stdio.h>
#include<conio.h>

union person
{
    char name[20];
    int age;
    float weight;
};

void main()
{
    union person p1;
    union person *ptr;

    ptr = &p1;

    printf("Enter name\t:");
    scanf("%s",ptr->name);
    printf("Name\t:%s",ptr->name);

    printf("\n\nEnter age\t:");
    scanf("%d",&ptr->age);
    printf("Age\t:%d",ptr->age);

    printf("\n\nEnter weight\t:");
    scanf("%f",&ptr->weight);
    printf("Weight\t:%f",ptr->weight);

    getch();
}

Output

Enter name      :neha
Name    :neha

Enter age       :30
Age     :30

Enter weight    :75.5
Weight  :75.500000

Explanation

In the above program, a union 'person' is defined and a variable 'p1' of union persoon type is declared. A union pointer 'ptr' is also declared. The address of 'p1' is stored in the 'ptr' pointer using
ptr = &p1;

Now, you can access the members of 'p1' using the 'ptr' pointer. To access members of union using the union variable, we used the dot (.) operator. But when we have a pointer of union type, we use arrow (->) to access union members.
ptr->age
ptr->weight

Note that,
ptr->age is equivalent to (*ptr).age
ptr->weight is equivalent to (*ptr).weight
Program for the same is shown in "Method 2" tab.

Program

#include<stdio.h>
#include<conio.h>

union person
{
    char name[20];
    int age;
    float weight;
};

void main()
{
    union person p1;
    union person *ptr;

    ptr = &p1;

    printf("Enter name\t:");
    scanf("%s",(*ptr).name);
    printf("Name\t:%s",(*ptr).name);

    printf("\n\nEnter age\t:");
    scanf("%d",&(*ptr).age);
    printf("Age\t:%d",(*ptr).age);

    printf("\n\nEnter weight\t:");
    scanf("%f",&(*ptr).weight);
    printf("Weight\t:%f",(*ptr).weight);

    getch();
}

Output

Enter name      :nikhil
Name    :nikhil

Enter age       :32
Age     :32

Enter weight    :95.4
Weight  :95.400000