¤ 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.


Example:
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];

main()
{
	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);

		switch(subscriber[no_sub].sub_type)
		{
			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);
				break;

			case 'O':
			case 'o':
				printf("\nOrganisation Name: "); 
				gets(subscriber[no_sub].categ.on.orgname);
				fflush(stdin);
				break;

			default:
				printf("\nError! Wrong Subscriber Type entered.\n");
				continue;
		}

		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("\nENTER TELEPHONE NUMBERS OF THIS SUBCRIBER");
			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 {
				connections++;
				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');		
		}
		no_sub++;

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

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




Share:




comments powered by Disqus


Web Service Offers

Accounting System for Small Business
5,999 4,999 (16.67% off)
per Year

Ecommerce on the Cloud

An online store hosted on the Cloud. Sell unlimited products. Integrated business functions. Well-suited for high traffic website.

39,999 29,999 (25% off)

Ecommerce Premium

An e-commerce website well-suited for companies having a large portfolio of products. Sell unlimited products. Manage both offline and online sales from one system.

40,000 25,000 (37.5% off)

Ecommerce Business

Launch your online business. Sell up to 5000 products. Collect payment via multiple online and offline payment methods.

35,000 25,000 (28.57% off)

Ecommerce Pro

Get a Mobile friendly online store front. Sell up to 1000 products.

35,000 25,000 (28.57% off)

Ecommerce Starter

Start selling your products online. Scale up as your business grows.

35,000 25,000 (28.57% off)

Website on the Cloud

Custom built, responsive corporate website hosted on the cloud. Mirrored on 3 servers. Includes visitor signup with CRM functions/

19,999 9,999 (50% off)

Website Corporate

Custom built, responsive corporate website with CRM. Our most popular website plan.

19,000 9,000 (52.63% off)

Website Business - 1000 Pages

Affordable website plan for small business. Custom built - quick page download, automatic SEO, mobile & tablet friendly.

18,000 8,000 (55.56% off)

Website Business - 500 Pages

Affordable website plan for small business. Custom built - quick page download, automatic SEO, mobile & tablet friendly.

17,500 7,500 (57.14% off)

Website Business - 100 Pages

Affordable website plan for small business. Custom built - quick page download, automatic SEO, mobile & tablet friendly.

17,000 7,000 (58.82% off)

Website Business - 50 Pages

Affordable website plan for small business. Custom built - quick page download, automatic SEO, mobile & tablet friendly.

16,500 6,500 (60.61% off)

Website Business - 25 Pages

Affordable website plan for small business. Custom built - quick page download, automatic SEO, mobile & tablet friendly.

16,000 6,000 (62.5% off)

Website Starter - 5 Pages

Get started with your own website at most affordable cost.

15,000 5,000 (66.67% off)


Looking to build a website?
Launch a 5 page website in 1 day at only Rs.499/year. Hosting 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