ProDeveloperTutorial.com

Tutorials and Programming Solutions
Menu
  • Shell Scripting
  • System Design
  • Linux System Programming
  • 4g LTE
  • Coding questions
  • C
  • C++
  • DSA
  • GIT
  • 450 DSA Cracker
  • 5G NR
  • O-RAN

Chapter 9: C language structure and Union

prodevelopertutorial August 13, 2018

In this chapter we shall learn about:

  1. Structure Introduction
  2. Declaration and initialization of structure
  3. Size of a structure.
  4. Bit fields
  5. Structure padding
  6. Structure with in a structure
  7. Array of Structure
  8. Pointer to structure
  9. Structure and functions
  10. Typedef
  11. Unions
  12. Enums

 

1. Structure Introduction:

 

Structure is a user defined data type. It is made with the combination of pre-defined data types and packed in to a different data type, name given by the programmer. “struct” is the keyword used to define a structure.

 

Use Case: For example, to store the information of student such as name, age, student id, class, marks different data types are needed. At this point we define a structure and use it.

 

2. Declaration and initialization of structure

 

A structure can be declared as shown below.

struct <structure_name>
{
	data-type variable_name_1;
	data-type variable_name_2;
};

 

“struct” keyword is used to create a structure. At the end of the structure semi-colon should be used to indicate end of structure. The variables inside a structure are called as members of structure.

 

Example:

struct student_details
{
	int roll_no;
	char name [20];
};

Below is the syntax on how to initialize a structure:

struct <structure_name> <structure_variable_name>

Example:

struct student_details details;

 

Accessing structure members:

Once you initialized a structure, the members can be accessed by using dot “.” Operator. In further topic we shall see how to access using arrow (->) operator.

Note: A structure be created inside a function.

 

3. Size of structure

 

The size of a structure is the sum of all the members of the structure and also their placement order.

 

Example 1. Size of structure when all the members type is same.

#include<stdio.h>

struct example_1 
{
	int num_1;
	char c;
	int num_2;

};

struct example_2 
{
	int num_1;
	int num_2;

};

int main()
{
	struct example_1 ex_1;
	struct example_2 ex_2;
	
	printf("The size of structure 1 is %d\n", sizeof(ex_1) );
	printf("The size of structure 2 is %d\n", sizeof(ex_2) );


	return 0;
}

Output:

The size of structure 1 is 12
The size of structure 2 is 8

 

Form the above output we can see that, in the first structure, even though the result should be [4 + 1 + 4] = 9, it is 12. Compiler has added extra 3 bytes after char. Making it easier to read.

The above behavior is called as structure padding. This topic is described below.

 

4. Bit fields

Bit fields are used to provide exact amount of space for a variable. For example, if a variable is holding the value 0 or 1, 1 bit is enough to store the value. If a variable is holding the value between 0 to 3, then 2 bits are enough to hold the value. Hence we use bit fields in those cases. Thus saving memory space.

 

Example program to show bit fields working and the structure size.

#include<stdio.h>

struct example_1 
{
	unsigned num_1 : 1;
	unsigned num_2 : 1;

};


struct example_2
{
	int num_1;
	int num_2;

};

int main()
{

	struct example_1 ex_1;
	struct example_2 ex_2;

	printf("The size of structure 1 is %d\n", sizeof(ex_1) );
	printf("The size of structure 2 is %d\n", sizeof(ex_2) );
	
	return 0;
}

Output:

The size of structure 1 is 4
The size of structure 2 is 8

Here we see that structure 1 is occupying 4 bytes, that is because by default it will take the size of a word i.e. 4 bytes. But only 2 bytes will be in use.

 

5. Structure padding

Compiler aligned the data in memory so that it can read one word [4 bytes] at a time. This is done by inserting empty space between uneven data type. This helps to increase the efficiency of the compiler. Padding is on by default.

Example to show structure padding.

 

Structure padding can be turned off,  this concept is called a packing. In GCC it can be turned off by adding “__attribute__((__packed__))” while creating the structure.

 

Example to show structure packing:

#include<stdio.h>

struct example_1 
{
	int num_1;
	char c;
	int num_2;

};

struct __attribute__((__packed__)) example_2 
{
	int num_1;
	char c;
	int num_2;

};

int main()
{
	struct example_1 ex_1;
	struct example_2 ex_2;
	
	printf("The size of structure 1 is %d\n", sizeof(ex_1) );
	printf("The size of structure 2 is %d\n", sizeof(ex_2) );


	return 0;
}

 

Output:

The size of structure 1 is 12
The size of structure 2 is 9

The structure 2 is switched off the structure padding.

6. Structure with in a structure

As we know that a structure is a user defined data type. Hence different structure can be a member of another structure. This concept is called as structure within a structure.

 

Example of structure with in a structure.

#include<stdio.h>

struct time 
{
	int hour;
	int minute;

};

struct bike
{
	int bike_number;
	struct time start_time;
	struct time end_time;

};

int main()
{
	struct bike b1;

	b1.bike_number = 10345;
	b1.start_time.hour = 9;
	b1.start_time.minute = 45;

	b1.end_time.hour = 12;
	b1.end_time.minute = 43;

	printf("The bike number is %d\n",b1.bike_number );
	printf("The bike started at %d hour\n", b1.start_time.hour);
	printf("The bike started at %d minute\n", b1.start_time.minute);
	printf("==========================================\n");
	printf("The bike ended at %d hour\n", b1.end_time.hour);
	printf("The bike ended at %d minute\n", b1.end_time.minute);
	return 0;
}

Output:

The bike number is 10345
The bike started at 9 hour
The bike started at 45 minute
==========================================
The bike ended at 12 hour
The bike ended at 43 minute

 

7.  Array of Structure

Similar like arrays of predefined data types, we can also create structure arrays. And the structure members can be accessed by index of that array.

 

Example:

#include<stdio.h>

struct student 
{
	int marks;
	int rollNo;

};

int main()
{
	struct student stud[5]; // created of 5 structure

	for (int i = 0; i < 5; ++i)
	{
		//insert the data
		stud[i].marks = 90 + i;
		stud[i].rollNo = i;
		
	}

	for (int i = 0; i < 5; ++i)
	{
		//display the data
		printf("The student roll no is %d, his marks is %d\n", stud[i].rollNo, stud[i].marks );	
	}
	 
	return 0;
}

Output:

The student roll no is 0, his marks is 90
The student roll no is 1, his marks is 91
The student roll no is 2, his marks is 92
The student roll no is 3, his marks is 93
The student roll no is 4, his marks is 94

 

8. Pointer to structure

As you know that a pointer is a variable that holds the address of another variable, we can create a pointer variable of structure type and make it hold the address of another structure variable. Such a pointer is called as structure pointers.

 

Example to show simple structure pointer:

#include<stdio.h>

struct student 
{
	int marks;
	int rollNo;

};

int main()
{
	struct student stud; 
	struct student *stud_ptr = &stud; 

	stud_ptr->marks = 100;
	stud_ptr->rollNo = 38;


	printf("The roll number of the student is %d, marks is %d\n",stud_ptr->rollNo, stud_ptr->marks );

	return 0;
}

Output:

The roll number of the student is 38, marks is 100

 

9.  Structure and functions

 

Like normal variable, the structure variables can also be passed to a function by value or by address.

Example of a function accepting structure object as its parameter.

struct book
{
	char bookName[10];
	int price;
	int bookID;
}bookObj ;

void main()
{
  display( &bookObj);
}

void display(struct book *bookObj)
{

}

 

10. Typedef

Typedef is used to give a data type a new name. This can be used with primitive data types and also with user defined data types like structures and unions.

 

Syntax:

typedef <data_type_name> <new_name>;

Example:

typedef  int  MyInt;

 

Note: Semicolon is important at the end.

Example to show typedef for structures.

#include<stdio.h>

typedef struct student 
{
	int marks;
	int rollNo;

}student;

int main()
{
	// so instead of declaring the structure variable as "struct student" 
	// we can directly use "student" as shown below 
	
	student stud;

	return 0;
}


 

11.Unions

Like structures, Union is also a user defined data type. It can also hold different types of data types. But the size of the union is equal to the largest data type size.

Union can hold only one object at a time, hence the size is equal to largest data type.

 

Example to show the size of union

#include<stdio.h>

union example
{
	int num;
	char ch;
};

struct example_with_union
{
	int num;
	union example ex;

};

int main()
{
	union example unionEx;
	struct example_with_union structEx;

	printf("The size of union is %d\n",sizeof(unionEx) );
	printf("The size of struct is %d\n",sizeof(structEx) );

}

Output:

The size of union is 4
The size of struct is 8

From the above, we can confirm that union can hold only 1 data and the size is equal to the largest size of the variable.

 

12. Enums

 

“enum” is the keyword used to define enumerated data type. If you want the user to restrict the number of choice that he can add to a variable, then the programmer can create a enum data type.

 

Example:

	enum week {Mon, Tues, Wed, Thurs, Fri, Sat, Sun }

Hence when you create a variable of type enum, you have to assign only those values that are defined in that variable.

	enum week day = Wed; // correct
	enum week day = Jan; // Wrong, because “Jan” is not defined in enum.

In enum, the constants for the values starts from 0, and incremented by 1 in subsequent values. This can be changed by adding values manually.

Example for enum and changing the default value:

#include<stdio.h>
enum week {Mon, Tues, Wed = 10, Thurs, Fri, Sat, Sun};


int main()

{
	enum week day = Mon;

	printf("The initial value of Monday = %d\n", Mon );
	printf("The value of Tuesday is = %d\n", Tues );
	printf("The value of Wednesday = %d. This is because we have changed the value of Wednesday\n", Wed );
	printf("The value of Thursday = %d\n", Thurs );


}

Output:

The initial value of Monday = 0
The value of Tuesday is = 1
The value of Wednesday = 10. This is because we have changed the value of Wednesday
The value of Thursday = 11

 

 

 

List Of Tutorials available in this website:

C Programming 20+ ChaptersC++ Programming 80+ Chapters
100+ Solved Coding QuestionsData Structures and Algorithms 85+ Chapters
System design 20+ ChaptersShell Scripting 12 Chapters
4g LTE 60+ ChaptersMost Frequently asked Coding questions
5G NR 50+ ChaptersLinux System Programming 20+ chapters

 

Share
Email
Tweet
Linkedin
Reddit
Stumble
Pinterest
Prev Article
Next Article

About The Author

prodevelopertutorial

Follow this blog to learn more about C, C++, Linux, Competitive Programming concepts, Data Structures.

Leave a Reply Cancel Reply

You must be logged in to post a comment.

ProDeveloperTutorial.com

Tutorials and Programming Solutions
Copyright © 2023 ProDeveloperTutorial.com
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies.
Do not sell my personal information.
Cookie SettingsAccept
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT