UNIT 4 STRUCTURES AND UNION
UNIT 4 STRUCTURES AND UNION
UNIT IV
Introduction - Need for Structure Data Type - Structure Definition – Structure Declaration –
Structures Within a Structure - Union - Programs using Structures and Unions - Storage Classes,
Pre-processor Directives.
STRUCTURES:
A Structure is a collection of one or more values of different data types, groupedtogether under a
single name. By using structures, we can make a group of variables,arrays, pointers etc.
Features of Structures:
❑ It is possible to copy the contents of all structure elements of different datatypes to another
structure variable of its type using assignment operator.
❑ Nesting of structure is possible.
❑ It is possible to pass structure elements to a function.
❑ It is possible to create structure pointers.
The following image shows the memory allocation of the structure employee that is defined in the above
example.
Here, struct is the keyword; employee is the name of the structure; id, name, and salary are the
members or fields of the structure. Let's understand it by the diagram given below:
We can declare a variable for the structure so that we can access the member of the structure easily.
There are two ways to declare structure variable:
1st way:
Let's see the example to declare the structure variable by struct keyword. It should be declared within the
main function.
struct employee
{ int id;
char name[50];
float salary;
};
Now write given code inside the main() function.
The variables e1 and e2 can be used to access the values stored in the structure. .
2nd way:
Let's see another way to declare variable at the time of defining the structure.
struct employee
{ int id;
char name[50];
float salary;
}e1,e2;
You can use a simpler syntax to initialize structures at the time of declaration:
This initializes e1 with the id 100, name "Alice Smith" and salary 25000 directly during declaration.
Example program:
#include<stdio.h>
struct student
{
int regno;
char name[30];
char branch[30];
int marks[10];
};
void main()
{
struct student s;
int total=0,i,n;
clrscr();
printf("Enter the reg.No");
scanf("%d",&s.regno);
fflush(stdin);
printf("\nEnter the name");
gets(s.name);
fflush(stdin);
printf("\nEnter the branch");
gets(s.branch);
printf("\nEnter the marks one by one\n");
for(i=0;i<7;i++)
{
scanf("%d",&s.marks[i]);
total=total+s.marks[i];
}
clrscr();
printf("\n\n STUDENTMARKPROCESSING \n");
printf("\n\tRegisterNo : %d",s.regno);
printf("\n\tNameoftheStudent :%s",s.name)
;printf("\n\tBranch :%s",s.branch);
printf("\n\tEnglish :%d",s.marks[0]);
printf("\n\tMathematics :%d",s.marks[1]);
printf("\n\tChemistry :%d",s.marks[2]);
printf("\n\tPhysics :%d",s.marks[3]);
printf("\n\tComputer Programming:%d",s.marks[4]);
printf("\n\tElectronicDevices :%d",s.marks[5]);
if(s.marks[0]>=50&&s.marks[1]>=50&&s.marks[2]>=50&&s.marks[3]>=50&&s.marks[4]>=50&&s.
marks[5]>=50&&s.marks[6]>=50)
printf("\n\tResult :PASS");
else
printf("\n\tResult :FAIL");
printf("\n\tTotal :%d",total);
getch();
}
OUTPUT:
Enter the reg.No 101
Enter the name aarthi
Enter the branch cse
Enter the marks one by one89
90
99
98
99
88
STUDENTMARKPROCESSING
Register No :101
Name of the Student :aarthi
Branch : cse
English :89
Mathematics :90
Chemistry :99
Physics :98
Computer Programming :99
Electronic Devices :88
Result :PASS
Total :641
Array of Structures in C
An array of structures in C can be defined as the collection of multiple structures variables where each
variable contains information about different entities. The array of structures in C are used to store
information about multiple entities of different data types. The array of structures is also known as the
collection of structures.
Let's see an example of an array of structures that stores information of 5 students and prints it.
#include<stdio.h>
#include <string.h>
struct student{
int rollno;
char name[10];
};
int main(){
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++){
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
}
printf("\nStudent Information List:");
for(i=0;i<5;i++){
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
return 0;
}
Output:
Structure Pointer
The structure pointer points to the address of a memory block where the Structure is being stored. Like
a pointer that tells the address of another variable of any data type (int, char, float) in memory. And here,
we use a structure pointer which tells the address of a structure in memory by pointing pointer
variable ptr to the structure variable.
The declaration of a structure pointer is similar to the declaration of the structure variable. So, we can
declare the structure pointer and variable inside and outside of the main() function. To declare a pointer
variable in C, we use the asterisk (*) symbol before the variable's name.
We can also initialize a Structure Pointer directly during the declaration of a pointer.
As we can see, a pointer ptr is pointing to the address structure_variable of the Structure.
Access Structure member using pointer:
There are two ways to access the member of the structure using Structure pointer:
Program to access the structure member using structure pointer and the dot operator
Let's consider an example to create a Subject structure and access its members using a structure pointer
that points to the address of the Subject variable in C.
Pointer.c
#include <stdio.h>
int main()
{
struct Subject sub; // declare the Subject variable
struct Subject *ptr; // create a pointer variable (*ptr)
ptr = ⊂ /* ptr variable pointing to the address of the structure variable sub */
Output:
Program to access the structure member using structure pointer and arrow (->) operator
Let's consider a program to access the structure members using the pointer and arrow (->) operator in C.
Pointer2.c
#include <stdio.h>
int main()
{
// store the address of the emp1 and emp2 structure variable
ptr1 = &emp1;
ptr2 = &emp2;
printf ("\n Display the Details of the Employee using Structure Pointer");
printf ("\n Details of the Employee (emp1) \n");
printf(" Name: %s\n", ptr1->name);
printf(" Id: %d\n", ptr1->id);
printf(" Age: %d\n", ptr1->age);
printf(" Gender: %s\n", ptr1->gender);
printf(" City: %s\n", ptr1->city);
Output:
Enter the name of the Employee (emp1): John
Enter the id of the Employee (emp1): 1099
Enter the age of the Employee (emp1): 28
Enter the gender of the Employee (emp1): Male
Enter the city of the Employee (emp1): California
Second Employee:
Enter the name of the Employee (emp2): Maria
Enter the id of the Employee (emp2): 1109
Enter the age of the Employee (emp2): 23
Enter the gender of the Employee (emp2): Female
Enter the city of the Employee (emp2): Los Angeles
// C program to implement
// the above approach
#include <stdio.h>
#include <string.h>
// Declaration of the
// dependent structure
structEmployee
{
int employee_id;
char name[20];
int salary;
};
// Declaration of the
// Outer structure
struct Organisation
{
char organisation_name[20];
char org_number[20];
org.emp.employee_id = 101;
strcpy(org.emp.name, "Robert");
org.emp.salary = 400000;
strcpy(org.organisation_name, "XXXXXXXX");
strcpy(org.org_number, "XXX123768");
Output:
The size of structure organisation : 68
Organisation Name : XXXXXXXX
Organisation Number : XXX123768
Employee id : 101
Employee name : Robert
Employee Salary : 400000
2. By Embedded nested structure: Using this method, allows to declare structure inside a structure
and it requires fewer lines of code.
When the structure variable of the inner structure is declared at the end of the inner structure. Below is
the C program to implement this approach:
// C program to implement
// the above approach
#include <stdio.h>
#include <string.h>
// Driver code
int main()
{
struct Organisation org;
org.emp.employee_id = 101;
strcpy(org.emp.name, "Robert");
org.emp.salary = 400000;
strcpy(org.organisation_name, "XXXXXXXX");
strcpy(org.org_number, "XXX123768");
Output:
The size of structure organisation : 68
Organisation Name : XXXXXXX
Organisation Number : XXX123768
Employee id : 101
Employee name : Robert
Employee Salary : 400000
Typedef:
Example:
Now myint is an alias of int. From now on we can declare new int variables using myint
instead of int keyword.
myint i = 0;
struct Point{
int x;
int y;
};
typedef struct Point Pt;
int main() {
Pt p1;
p1.x = 1;
p1.y = 3;
printf("%d \n", p1.x);
printf("%d \n", p1.y);
return 0;
}
Method 2
#include<stdio.h>
UNION:
Union is a variable, which is similar to the structure. It contains data elements ofdifferent data
types. The Union requires bytes that are equal to the number of bytesrequiredfor the
largestmembers.
We need to define a variable of the union type to start using union members. There are two methods
using which we can define a union variable.
1. With Union Declaration
2. After Union Declaration
1. Defining Union Variable with Declaration
union union_name {
datatype member1;
datatype member2;
...
} var1, var2, ...;
2. Defining Union Variable after Declaration
union union_name var1, var2, var3...;
where union_name is the name of an already declared union.
We can access the members of a union by using the ( . ) dot operator just like structures.
var1.member1;
where var1 is the union variable and member1 is the member of the union.
The above method of accessing the members of the union also works for the nested unions.
var1.member1.memberA;
Here,
var1 is a union variable.
member1 is a member of the union.
memberA is a member of member1.
Initialization of Union in C
The initialization of a union is the initialization of its members by simply assigning the value to it.
var1.member1 = some_value;
One important thing to note here is that only one member can contain some value at a given
instance of time.
Example of Union
// driver code
int main()
{
return 0;
}
Output
T he value stored in member1 = 15
Size of Union
The size of the union will always be equal to the size of the largest member of the array.
#include <stdio.h>
union MyUnion {
int num1;
float num2;
};
int main()
{
union MyUnion UN;
UN.num1 = 10;
printf("\nNum1: %d, Num2: %f", UN.num1, UN.num2);
UN.num2 = 10.34F;
printf("\nNum1: %d, Num2: %f", UN.num1, UN.num2);
return 0;
}
Output
Size of union: 4
Num1: 10, Num2: 0.000000
Num1: 1092972708, Num2: 10.340000
3. All the data members are Only the last stored data element is
available in the primary memory available in the primary memory at any
at any time of execution. time of execution.
4. Since memory is allocated for all Since memory is not allocated for all
the data members, nodata is the data member, only one data is
available and other data is
deleted in the primarymemory
Deleted from the primary memory
Storage Class Specifiers for Variables
• Variables are declared by the type of data they can hold
• The name of a variable is associated with a memory location within the computer where
the value assigned to the variable is stored in the form of bits.
• C provides four storage class specifiers to indicate where the variables
would be stored
how long they would exist
what would be their region of existence
what would be the default values
• Four storage class specifiers are
1. Automatic
2. External
3. Register
4. Static
Output
a = 5
a = 10
i = 4199232
a = 5
Output
The value of m1 : 5
The value of m2 : 10
#include <stdio.h>
int main()
{
void show(void);
printf(“\n First Call of show()”);
show();
printf(“\n Second Call of show()”);
show();
printf(“\n Third Call of show()”);
show();
return 0;
}
void show(void)
{static int i;
printf(“\n i=%d”,i);
i++;}
Output
First Call of show()
i=0
Second Call of show()
i=1
Third Call of show()
i=2
Example : C program that demonstrates the use of the static variables and functions
#include <stdio.h>
void func(void);
static int count = 5; /* global variable */
int main() {
while(count--) {
func();
}
return 0;
}
/* function definition */
void func( void ) {
static int i = 5; /*local static variable */
i++;
printf("i is %d and count is %d\n", i, count);
}
Output
i is 6 and count is 4
i is 7 and count is 3
i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0
Output
Value of i in pgm2.c=10
Value of i in pgm1.c=10
Example : C program that demonstrates the use of the extern variables and functions
Value of i in pgm1.c=20
Pre-processor Directives
Preprocessor programs provide preprocessor directives that tell the compiler to preprocess the source
code before compiling. All of these preprocessor directives begin with a ‘#’ (hash) symbol. The ‘#’
symbol indicates that whatever statement starts with a ‘#’ will go to the preprocessor program to get
executed.
List of preprocessor directives in C
The following table lists all the preprocessor directives in C:
Preprocessor Directives Description
These preprocessors can be classified based on the type of function they perform.
Types of C Preprocessors
There are 4 Main Types of Preprocessor Directives:
1. Macros
2. File Inclusion
3. Conditional Compilation
4. Other directives
1. Macros
In C, Macros are pieces of code in a program that is given some name. Whenever this name is
encountered by the compiler, the compiler replaces the name with the actual piece of code.
The ‘#define’ directive is used to define a macro.
Syntax of Macro Definition
#define token value
where after preprocessing, the token will be expanded to its value in the program.
// macro definition
#define LIMIT 5
int main()
{
for (int i = 0; i < LIMIT; i++) {
printf("%d \n", i);
}
return 0;
}
Output
0
1
2
3
4
In the above program, when the compiler executes the word LIMIT, it replaces it with 5. The
word ‘LIMIT’ in the macro definition is called a macro template and ‘5’ is macro expansion.
Note There is no semi-colon (;) at the end of the macro definition. Macro definitions do not need a semi-
colon to end.
int main()
{
int l1 = 10, l2 = 5, area;
return 0;
}
Output
Area of rectangle is: 50
We can see from the above program that whenever the compiler finds AREA(l, b) in the program, it
replaces it with the statement (l*b). Not only this, but the values passed to the macro template AREA(l,
b) will also be replaced in the statement (l*b). Therefore AREA(10, 5) will be equal to 10*5.
2. File Inclusion
This type of preprocessor directive tells the compiler to include a file in the source code program.
The #include preprocessor directive is used to include the header files in the C program.
There are two types of files that can be included by the user in the program:
Standard Header Files
The standard header files contain definitions of pre-defined functions like printf(), scanf(), etc. These
files must be included to work with these functions. Different functions are declared in different header
files.
For example, standard I/O functions are in the ‘iostream’ file whereas functions that perform string
operations are in the ‘string’ file.
Syntax
#include <file_name>
where file_name is the name of the header file to be included. The ‘<‘ and ‘>’ brackets tell the compiler
to look for the file in the standard directory.
User-defined Header Files
When a program becomes very large, it is a good practice to divide it into smaller files and include them
whenever needed. These types of files are user-defined header files.
Syntax
#include "filename"
The double quotes ( ” ” ) tell the compiler to search for the header file in the source file’s directory.
3. Conditional Compilation
Conditional Compilation in C directives is a type of directive that helps to compile a specific portion of
the program or to skip the compilation of some specific part of the program based on some conditions.
There are the following preprocessor directives that are used to insert conditional code:
1. #if Directive
2. #ifdef Directive
3. #ifndef Directive
4. #else Directive
5. #elif Directive
6. #endif Directive
#endif directive is used to close off the #if, #ifdef, and #ifndef opening directives which means the
preprocessing of these directives is completed.
Syntax
#ifdef macro_name
// Code to be executed if macro_name is defined
#ifndef macro_name
// Code to be executed if macro_name is not defined
#if constant_expr
// Code to be executed if constant_expression is true
#elif another_constant_expr
// Code to be excuted if another_constant_expression is true
#else
// Code to be excuted if none of the above conditions are true
#endif
If the macro with the name ‘macro_name‘ is defined, then the block of statements will execute normally,
but if it is not defined, the compiler will simply skip this block of statements.
Example
The below example demonstrates the use of #include #if, #elif, #else, and #endif preprocessor directives.
// defining PI
#define PI 3.14159
int main()
{
#ifdef PI
printf("PI is defined\n");
#elif defined(SQUARE)
printf("Square is defined\n");
#else
#error "Neither PI nor SQUARE is defined"
#endif
#ifndef SQUARE
printf("Square is not defined");
#else
printf (“Square is defined" );
#endif
return 0;
}
Output
PI is defined
Square is not defined
4. Other Directives
Apart from the above directives, there are two more directives that are not commonly used. These are:
1. #undef Directive
2. #pragma Directive
1. #undef Directive
The #undef directive is used to undefine an existing macro. This directive works as:
#undef LIMIT
Using this statement will undefine the existing macro LIMIT. After this statement, every “#ifdef LIMIT”
statement will evaluate as false.
Example
The below example demonstrates the working of #undef Directive.
#include <stdio.h>
// defining MIN_VALUE
#define MIN_VALUE 10
int main() {
// Undefining and redefining MIN_VALUE
printf("Min value is: %d\n",MIN_VALUE);
printf("Min value after undef and again redefining it: %d\n", MIN_VALUE);
return 0;
}
Output
Min value is: 10
Min value after undef and again redefining it: 20
2. #pragma Directive
This directive is a special purpose directive and is used to turn on or off some features. These types of
directives are compiler-specific, i.e., they vary from compiler to compiler.