¤ Home » Programming » C Tutorial » Working with Unions in C

Working with Unions in C

Unions are structures that contain members whose individual data types may differ from one another. Moreover, the members that comprise a union share the same storage area. Thus if we consider the structure to be a road map to access memory of the computer for storing and accessing data objects, then a union provides various road maps for the same memory space.

Let us consider an example that illustrates the usage of unions. Here we need to store student information (student record), that consists of two parts, fixed and variable. For every student, name, roll number, grade and status form the fixed part, whereas the variable data is an union of jee_marks and gate_score depending on whether the student is an undergraduate student or a post graduate student.

Only one of the members of the union can be accessed at a given point of time depending on the status of the student (status is 'G' for graduates, 'U' for undergraduates).

For students who have already graduated gate_score is to be considered, while jee_marks is considered for undergraduates.

Though union may consist of two members of different data types, the memory space reserved is always of the same size. The memory space allocated/reserved will equal the size of the member whose storage space requirement is maximum among all the members in the union.

typedef struct {
	char first_name[21];
	char middle_name[21];
	char last_name[21];
} name; 

struct student {
	name  student_name;
	int   roll_no;
	float grade;
	char  status;
	union {
		int jee_marks;
		float gate_score;
	} level;
} a, b, c; 

A group of contiguous structures as elements including unions can be implemented using arrays. The below declaration defines an array for a class of 40 students.

struct student {
} class[40];

Let us look at a practical implementation.

/* Program to demonstrate array of structures that include unions */
#include <stdio.h>
#define MAX_SUB 100 

struct pname{
	char fname[21];
	char lname[21];

struct oname {
	char orgname[31];

struct tele{
	char sub_type; /* 'P' for person, 'O' for organisation */
	union {
		struct pname pn;
		struct oname on; 
	} categ;
	char address[31];
	int no_connections;
	char (*telephones)[8];

struct tele subscriber[MAX_SUB];

	int no_sub = 0, connections = 0;
	char rep = 'Y';
	do {
		printf("\nSubscriber's type (P/O)?: ");
		scanf("%c", &subscriber[no_sub].sub_type); fflush(stdin);

			case 'p':
			case 'P':
				printf("\nFirst Name: ");
				gets(subscriber[no_sub].categ.pn.fname); fflush(stdin);
				printf("\nLast Name: ");
				gets(subscriber[no_sub].categ.pn.lname); fflush(stdin);

			case 'O':
			case 'o':
				printf("\nOrganisation Name: "); 

				printf("\nError! Wrong Subscriber Type entered.\n");

		printf("\nSubscriber's Address: ");
		gets(subscriber[no_sub].address); fflush(stdin);

		printf("\nNumber of Connections: ");
		scanf("%d", &subscriber[no_sub].no_connections); fflush(stdin);

		if(subscriber[no_sub].no_connections > 0)
			printf("\nMaximum Number of Connections %d\n", subscriber[no_sub].no_connections);
			printf("(Enter 0 to finish entering telephone numbers)\n");
			subscriber[no_sub].telephones=(char (*)[])malloc(subscriber[no_sub].no_connections * 8);
			connections = -1;
			do {
				printf("\nConnection Number %d: ", connections+1);
				scanf("%s", subscriber[no_sub].telephones[connections]); fflush(stdin);
			} while(connections != (subscriber[no_sub].no_connections - 1) && *(*(subscriber[no_sub].telephones + connections)) != '0');		

		printf("\nDo you want to process another Subscriber (Y/N)? ");
		rep = getchar();
		getchar(); //this getchar takes away the enter key character

	} while((rep == 'y' || rep == 'Y') && (no_sub < MAX_SUB));


comments powered by Disqus

Buy Domain & Hosting from the most reliable and trusted company - WebServicesWorldWide.com.

Looking to build a website?
Launch a 20 page website in 1 day at only Rs.200/month or US$ 3.19/month. Hosting & Email included.

About the Author

Rajeev Kumar
CEO, Computer Solutions
Jamshedpur, India

Rajeev Kumar is the primary author of How2Lab. He is a B.Tech. from IIT Kanpur with several years of experience in IT education and Software development. He has taught a wide spectrum of people including fresh young talents, students of XLRI, industry professionals, and govt. officials.

Rajeev has founded Computer Solutions & WebServicesWorldwide.com, and has hands-on experience of building variety of web applications and portals, that include - SAAS based ERP & e-commerce systems, independent B2B, B2C, Matrimonial & Job portals, and many more.

Copyright © How2Lab.com. All rights reserved.

Refer a friend | Sitemap | Disclaimer | Privacy Policy