top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Please explain pointer to array of union in c with a suitable example?

+1 vote
418 views
Please explain pointer to array of union in c with a suitable example?
posted Mar 16, 2016 by Mohammed Hussain

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button
What explanation you are expecting for this question ? Please clarify your query.

1 Answer

0 votes

Here we will be learning about pointer to union i.e pointer which is capable of storing the address of an union in c programming.

Pointer to union:

Pointer which stores address of union is called as pointer to union

Syntax

union team t1;    //Declaring union variable
union team *sptr; //Declaring union pointer variable 
sptr = &t1;       //Assigning address to union pointer

In the above syntax that we have shown –

Step 1 : We have declared a variable of type union.

Step 2 : Now declare a pointer to union

Step 3 : Uninitialized pointer is of no use so need to initialize it

#include<stdio.h>

union team {
  char *name;
  int members;
  char captain[20];
};

int main()
{
union team t1,*sptr = &t1;

t1.name = "India";
printf("\nTeam : %s",(*sptr).name);
printf("\nTeam : %s",sptr->name);

return 0;
}

Output :

Team = India
Team = India

Program explanation

sptr is pointer to union address.
-> and (*). both represents the same.
These operators are used to access data member of structure by using union’s pointer.

Summary

In order to access the members of union using pointer we can use following syntax –

Code Explanation
(*sptr).name Used for accessing name
sptr->name Used for accessing name

answer May 31, 2016 by Manikandan J
...