0% found this document useful (0 votes)
10 views

Unit - 5 Notes

The document discusses structures and unions in C programming. It defines structures as a way to group different data types together under a single name. The document explains how to declare and initialize structures, access structure members, create nested structures and arrays of structures. It also discusses passing structures to functions.

Uploaded by

Temp
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Unit - 5 Notes

The document discusses structures and unions in C programming. It defines structures as a way to group different data types together under a single name. The document explains how to declare and initialize structures, access structure members, create nested structures and arrays of structures. It also discusses passing structures to functions.

Uploaded by

Temp
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

UNIT IV

STRUCTURES AND UNIONS

Syllabus:

Introduction – Need for structure data type – Structure definition - Structure Declaration – Structure within a
structure - Unions – Programs using structure and union – Storage classes – The Preprocessor Directives.

Introduction:

5. STRUCTURES AND UNIONS

5.1 Structures and Unions

Structure is defined as collection of different data types.


Structure is a method of packing data of different types. It collects different data type values under single
variable name.
 As we know that Array is collection of the elements of similar type, but many time we will need to
store the elements of different data types.
 Collection of different data type items it is not possible using an array.
 When we require using a collection of different data items of different data types we can use a
Structure.
Array is a homogeneous collection of data whereas Structure and Union are heterogeneous collection of data.
Union is also as collection elements of different data type, but the difference between the structure and union
lies in the way the compiler allocates the memory.

5.1.1 Need for Structure

In most of the cases, we need to store information that is related to each other. But the information may not be
of same type.

Consider an example where we have to store the details of book. (pages, name, price)

Here the name should be stored as character array, the pages should be stored as integer, and the price should be
stored as float.
We cannot do this with an array, since array is a collection of similar data types.

5.1.2 Structure Declaration

Syntax
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeber;
};

Example

struct book
{
char name[20];
float price;
int pages;
};
Note :
Each variable declared in Structure is called member.
The members in the above structure are
char name[20];
float price;
int pages;
Name given to structure is called as tag
Example: book

5.1.3 Structure Initialization

A structure can be initialized as follows

struct focp ={“c++”,240.75,300};


The values will be assigned in the order that they are declared.

A structure can be initialized at the end of the structure like

struct book
{
char name[20];
float price;
int pages;
}focp ={“c++”,240.75,300};

or it can be initiialized in the main function as follows

struct book
{
char name[20];
float price;
int pages;
};

void main()
{
struct focp ={“c++”,240.75,300};
}

Note: focp is the structure varaible that is used to access the members of the structure.

Rules for structure initialization

 The order of data type of the structure members in the declaration, should match with the order in the
initialization.
 Individual structure members cannot be initialized separately
 The uninitialized structure members will be assigned default values(0 for int and float and ‘\0’ for
character)
5.1.4 Accessing the Elements of the Structure

Whenever a structure is created, we should also create a Structure Variable to access the elements of structure.

The memory is allocated for the structure, only when the Structure Variable is created.
A structure can have any number of Structure Variable.

Each Structure Variable will have its own copy of the elements of the structure.

Declarating Structure Variable

Syntax

struct StructureName StructureVariablesName;

Example

struct book focp;

This is how the memory will be allocated for the structure variables.

30 bytes
book1

name[20]
20 bytes

price
4 bytes

pages
2 bytes

The members of the structure can accessed using structure variable with a dot(.) operator.

Example

focp.pages;

focp.name;

Different Ways of Declaring Structure Variable

Immediately after Structure Template

struct book
{
char name[20];
float price;
int pages;
}focp;
// 'focp' is name of Structure variable

Inside the main function

struct book
{
char name[20];
float price;
int pages;
}focp;
struct book focp;

Declaring Multiple Structure Variables

struct book
{
char name[20];
float price;
int pages;
}focp1,focp2,focp3;
We can declare multiple variables separated by comma directly after closing curly braces.

Accessing members of a structure

There are two types of operators used for accessing members of a structure.
 Member operator(.)
 Structure pointer operator(->)
Example
focp.pages;

focp.name;
focp.price;

Example Program
#include<stdio.h
struct book
{
char name[20];
float price;
int pages;
}focp1;
void main()
{
printf(“Enter The Book Name = ”);
scanf(“%s”,focp1.name);
printf(“Enter The Book Price = ”);
scanf(“%f”,&focp1.price);
printf(“Enter The Book Pages = ”);
scanf(“%d”,&focp1.pages);

printf(“Book Name = %s”,focp1.name);


printf(“Book Price = %f”,focp1.price);
printf(“Book Pages = %d”,focp1.pages);
}
Note : Dot operator has Highest Priority than unary, arithmetic, relational and logical Operators

5.1.5 Structure within Structure

A structure within a structure is called as nested structure. It is also called as embedded structure.

Example

struct book
{
char name[20];
struct price
{
float priceInRupees;
float priceInDollars;
};
int pages;
};

book 30 bytes

name[20]
20 bytes
8 bytes
price price
8 bytes priceInRupees
4bytes

pages priceInDollars
4 bytes
2 bytes

5.1.6 Arrays of Structure


An array of structure variable is called as array of structures.

For Example, in the structure book if we create an array of structure variables as follows

struct book
{
char name[20];
float price;
int pages;
}focp[3];

void main()
{
struct focp[0] ={“Advanced c”,240.75,300};
struct focp[1] ={“c”,290.75,270};
struct focp[2] ={“basic C”,300.00,380};
}
Example Program
#include<stdio.h>
#include<conio.h>

struct Employee
{
int ssn;
char ename[20];
char dept[20];
}emp[3]; //array of structure
void main()
{
int i,sum;
for(i=0;i<3;i++)
{
printf("\nEnter the Employee Details : ");
scanf("%d %s %s",&emp[i].ssn,emp[i].ename,emp[i].dept);
}
//Print Employee Details
for(i=0;i<3;i++)
{
printf("nEmployee SSN : %d",emp[i].ssn);
printf("nEmployee Name : %d",emp[i].ename);
printf("nEmployee Dept : %d",emp[i].dept);
}
getch();
}
Output :
Enter the Employee Details : 1 Ram Testing
Employee SSN : 1
Employee Name : Ram
Employee Dept : Testing

Initializing Array of Structure


struct book
{
char bname[20];
int pages;
char author[20];
float price;
}b[3] = {
{"Let us C",700,"YPK",300.00},
{"Wings of Fire",500,"APJ Abdul Kalam",350.00},
{"Complete C",1200,"Herbt Schildt",450.00}
};

5.1.7 Passing Array of Structure

 Array of Structure can be passed to function as a Parameter.


 Function can also return Structure as return type.
Example

#include<stdio.h>
#include<conio.h>
struct Example
{
int num1;
int num2;
}s[3];
void accept(struct Example sptr[],int n)
{
int i;
for(i=0;i<n;i++)
{
printf("\nEnter num1 : ");
scanf("%d",&sptr[i].num1);
printf("\nEnter num2 : ");
scanf("%d",&sptr[i].num2);
}
}
void print(struct Example sptr[],int n)
{
int i;
for(i=0;i<n;i++)
{
printf("\nNum1 : %d",sptr[i].num1);
printf("\nNum2 : %d",sptr[i].num2);
}
}
void main()
{
int i;
clrscr();
accept(s,3);
print(s,3);
getch();
}
Output :
Enter num1 : 10
Enter num2 : 20
Enter num1 : 30
Enter num2 : 40
Enter num1 : 50
Enter num2 : 60
Num1 : 10
Num2 : 20
Num1 : 30
Num2 : 40
Num1 : 50
Num2 : 60
5.1.8 Self Referential Structure
A self-referential structure is a structure which refers to itself.

A self referential structure is used to create data structures like linked lists, stacks, etc.
Following is an example of this kind of structure:
Syntax
struct struct_name
{
datatype datatypename;
struct struct_name * pointer_name;
};

Example
struct LinkedList
{
int data;
struct LinkedList *address;
};
Here the structure LinkedList contains a varaible *address which is its own structure data type LinkedList
Calculate Size of Structure
Structure is used for collecting different data types together. There are different ways of calculating size of
structure.
Using sizeof Operator
Program
#include<stdio.h
struct book
{
char name[20]; // 20 x1  20 bytes
float price; // 4 bytes
int pages; // 2 bytes
}focp1;
void main()
{
printf(“Size of Structure = %d”,sizeof(focp1));
}
Output
Size of Structure = 26
20 + 4 + 2 =26
Uses / Applications of Structure
1. Implementing linked list, stack etc.

2. Creating the directory structure for a disk

5.1.9 Introduction to Union


Union is similar to the structure. It also contains members like structures, but it does not allocate memory for
every single member, but it allocates the memory only for the variable which requires largest memory.

Union and Structure


union stud struct stud
{ {
int roll; int roll;
char name[4]; char name[4];
int marks; int marks;
}s1; }s1;

Only one Member will be active at a time


Suppose we are accessing one data members of union then it is not possible to access other data members of
that union. This is because each data member shares same memory.
By Using Union we can Save Lot of Valuable Space
Syntax

union unionName
{
union_member1;
union_member2;
union_member3;
..
..
..
union_memberN;
}unionVariable;
Simple Example

union stud
{
int roll;
char name[4];
int marks;
}s1;

Where stud is the union name and s1 is the union variable that can access the members of the union.

Consider the example below to understand the way in which structure and union differs in memory
allocation

#include <stdio.h>
union job
{
char name[32]; // 32 bytes
float salary; // 4 bytes
int worker_no; // 2 bytes
}u;
struct job1
{
char name[32]; // 32 bytes
float salary; // 4 bytes
int worker_no; // 2 bytes
}s;
void main()
{
printf("size of union = %d",sizeof(u));
printf("\nsize of structure = %d", sizeof(s));
}
Output
size of union = 32
size of structure = 38
Explanation:
The amount of memory required to store a structure variables is the sum of memory size(32 + 4 + 2 = 38 bytes)
of all members.

But, the memory required to store a union variable is the memory required for largest element(32 bytes) of an
union

5.1.10 Structure Vs Union

Structure Union

i. Access Members

All the members of structure can be accessed


Only one member of union can be accessed at a time.
simultaneously.

ii. Memory Allocation

Memory is allocated for each and every Allocates memory for variable which variable require the
variable i.e. the memory allocated will be largest memory i.e. the memory allocated will be equal to
equal to the sum memory required for every the memory required, for the variable which needs largest
variable. memory.

iii. Initialization

every members of structure can be initialized Only the first member of a union can be initialized.

iv. Keyword

'struct' keyword is used to declare structure. 'union' keyword is used to declare union.

v. Syntax

struct struct_name union union_name


{ {
structure element 1; union element 1;
structure element 2; union element 2;
---------- ----------
---------- ----------
structure element n; union element n;
}struct_var_nm; }union_var_nm;

vi. Example

struct item_mst union item_mst


{ {
int rno; int rno;
char nm[50]; char nm[50];
}it; }it;

5.1.11 Programs using structure and union

5.1.12 Storage Classes

Refer : Section 2.6.5.5

5.2 The Preprocessor

 Is it possible to write C program that calls an user defined function before main() function?
 Can we have two main() function in same program.
Yes..... it is possible with the help of using Preprocessor

5.2.1 Introduction

 Pre processor is a program that processes our source program before compilation.
 Preprocessor directives are initialized at the beginning of the program before the main().
 Preprocessor always begins with # (hash) and does not require any semicolon at the end.
All the preprocessor process before the starting of actual compilation and create an intermediate file. In the
intermediate file all preprocessor statement is replaced by corresponding C code.During the compilation process
that intermediate file is deleted by compiler automatically.
 A set of commonly used preprocessor directives
Directive Description
#define Substitutes a preprocessor macro
#include Inserts a particular header from another file

#undef Undefines a preprocessor macro


#ifdef Returns true if the macro is defined
#ifndef Returns true if the macro is not defined

#if Tests whether a compile time condition is true


#else The alternative for #if

#elif #else an #if in one statement


#endif Ends preprocessor conditional

#error Prints error message on stderr


Issues special commands to the compiler, using
#pragma
a standardized method

Note : Program that Processes or Analyzes the source code file before Given to the Compiler is called as Pre-
Processor.
The preprocessor directives can be divided into four categories:
(a) Macro Expansion

(b) File Inclusion Directive or #include Directive

(c) Conditional Compilation

(d) Miscellaneous directives

5.2.2 Advantages of Preprocessor

5.2.3 Macro Expansion

5.2.3.1 Introduction

 Macro Expansion is a process where an identifier in a program is replaced by a string composed of one
or more tokens.
 The #define statement is used for macro expansion.
 Preprocessor replaces every occurrence of the identifier in the source code by that string .
 There are 2 types of macro definition
1. Simple Macro
2. Macro with argument.

Simple Macro
Syntax for #define

#define Macro_Template Macro_Expansion

Example

#define PI 3.14

Example program 1
Source Code before Processing by compiler:

#include<stdio.h>
#include<conio.h>
#define MAX 9
void main()
{
int i = MAX;
printf("Age of Child : %d",MAX);
getch();
}

Final Source Code after Processing by compiler:


void main()
{
int i = 9;
printf("Age of Child : %d",9);
getch();
}

Example Program 2

#include<stdio.h>
#define LIMIT 5
void main( )
{
int i ;
for ( i = 1 ; i <= LIMIT; i++ )
printf ( "\t %d", i ) ;
}

Output

1 2 3 4 5

Explanation

In the above program instead of using i<=5,we are writing as i<=LIMIT and defining LIMIT as 5. Here the
macro replaces every occurrence of limit as 5.

Example Program 3
#include <stdio.h>
#define PI 3.1415
void main()
{
int radius;
float area;
printf("Enter the radius: ");
scanf("%d",&radius);
area=PI*radius*radius;
printf("Area=%.2f",area);
}

Output

Enter the radius: 3


Area=28.27
Explanation

In the above program the identifier pi is replaced by the value 3.1415

Note: A macro definition should never end with a semicolon. A macro definition in capitals is a
convention not a rule.

How C Preprocessor Works


5.2.3.2 Advantages of Macro

1. Readability: Consider that we are going to use the value of pi(3.141592) in a program. Then we can define
that using macro as

# define PI 3.141592

because it will be more meaningful to use the value as PI rather than as 3.141592.

When someone other than the programmer reads the program, He/She can understand that PI is 3.141592 but
will be difficult for him/her to assume that 3.141592 as PI

2. Flexibility : If we have uses the value of pi, a hundred times in a program and at some instance we need to
change the value of pi from 3.141592 to 3.14 ,then we need not replace all the occurrence but only one
occurrence, i.e we can redefine the macro as

# define pi 3.14

5.2.3.3 Macro with Arguments


The macros that we have used so far are called simple macros. Macros can have arguments. Preprocessor
permits us to define more complex and more useful form of macros.

Syntax

#define Identifier(f1,f2,f3…..fn) String

Example

#define square(x) ( x * x )

Example Program 1

#include<stdio.h>
#define SQUARE(x) ( x * x )
void main( )
{
printf ( "Square of 3 = %d", SQUARE(3) ) ;
}
Output

Square of 3 = 9

Explanation

SQUARE(3) is expanded as (3 * 3 )

Example Program 2

#include <stdio.h>
#define PI 3.1415
#define area(r) (PI*r*r)
void main()
{
int radius;
float area;
printf("Enter the radius: ");
scanf("%d",&radius);
area=area(radius);
printf("Area=%.2f",area);
}
Output:

Enter the radius:12


Area= 452.38

Explanation:

area(radius) is expanded as 3.1415*12*12

Note: Macro are closely related to function concepts, but it is not a substitute for function.

5.2.3.4 Predefined Macros in C language

Predefined
Value
macro
__DATE__ String containing the current date

__FILE__ String containing the file name


__LINE__ Integer representing the current line number
If follows ANSI standard C, then value is a nonzero
__STDC__
integer

__TIME__ String containing the current time.

Example of using predefined Macros

C Program to find the current time:

#include <stdio.h>
void main()
{
printf("Current time: %s",__TIME__); //calculate the current time
}

Output

Current time: 19:54:39


5.2.2.5 Difference Between Macro and Function

No Macro Function
1 Macro is Preprocessed Function is Compiled

2 No Type Checking Type Checking is Done

3 Code Length Increases Code Length remains Same

4 Use of macro can lead No side Effect


to side effect

5 Speed of Execution is Speed of Execution is Slower


Faster

6 Before Compilation macro name is replaced During function call , Transfer of Control
by macro value takes place

7 Useful where small code appears many time Useful where large code appears many time

8 Generally Macros do not extend beyond one Function can be of any length
line

9 Macro does not Check Compile Errors Function Checks Compile Errors

Example Program 4

#define CUBE(x) (x*x*x)


void main()
{
int volume =CUBE(3+2);
printf("%d",volume);
}
What will be the output?
Actually the output is expected to be 125 ,but it is wrong.
Output
17
Explanation :
This program will be expanded as:

void main()
{
int volume =CUBE(3+2*3+2*3+2);
printf("%d",volume);
}
= 3+2*3+2*3+2
= 3+6+6+2
= 17

5.2.4 File Inclusion Directive or #include Directive

 File inclusive Directories are used to include user define header file inside C Program.
 File inclusive directives begins with #include
.
Syntax

#include "filename.h" or #include <filename.h>

It cause the entire content of the given filename to be include in the program, before the execution begins.

There are two possible Ways of including header file

Way 1 : Including Standard Header Files


#include<filename>
 Searches for the included File in Standard Library first.

Way 2 :User Defined Header Files are written in this way

#include"filename"
 Searches for the included File in Current Library first.
 If not found , then it Searches in Standard Library

Example Program
Including Predefined Files

#include <stdio.h> // Standard Header file


#include <conio.h> // Standard Header file
void main()
{
clrscr();
printf(“Welcome”);
getch();
}
Steps To implement Userdefined Files

Step 1 : First create a file Arithmetic.h which contains the following code:

int add (int x, int y)


{
return x+y;
}
int sub (int x, int y)
{
return x-y;
}
int mul(int x, int y)
{
return x*y;
}
int div (int x, int y)
{
return x/y;
}
Step 2 : Now create another c file Math.c which contains the following code

#include “Arithmetic.h” // User Defined File


void main( )
{
int a=10,b=5,t=0;
t=add(a,b);
printf(“Sum = %d”,t);
t=sub(a,b);
printf(“Subtract = %d”,t);
t=mul(a,b);
printf(“Multiplication = %d”,t);
t=div(a,b);
printf(“Division = %d”,t);
}

Output:

Sum = 15
Subtraction = 5
Multiplication = 50
Division = 2

5.2.5 Conditional Compilation

 Conditional compilation is the processes of making the compiler skip a block of source code by inserting
the preprocessing commands.
 Six directives are available to implement conditional compilation
#if #ifdef #endif #ifndef #else #elif.
 Conditional compilation means ,based on a condition, the compilation is done.
#If Directive

It is conditional compilation directive. That is if condition is true then it will compile the c programming code
otherwise it will not compile the c code.

Syntax 1

#if <Constant_expression>
-------------
-------------
#endif
If the constant expression returns a value of 0, then the condition will be false and the block of statements
between #if and #endif will be not be executed.

If the constant expression returns a non-zero value, then the condition will be true and the block of statements
between #if and #endif will be executed.

Example 1

#include<stdio.h>
#if 0
void main()
{
printf("Welcome");
}
#endif
Output

Run time error, undefined symbol _main

Explanation: The constant expression is 0 and so #if condition will false. So c code inside the #if condition
will not be executed. Since there is no main function, the compiler generates an error.

Note: The #else is similar to the #if directive, but in the case of #else directive the statements will be executed
only if the condition is false.

Syntax for #if and #else:

#if <Constant_expression>
-----------------
-----------------
#else
-----------------
-----------------
#endif
Example 2a

#include<stdio.h>
#if 5
void main()
{
printf("Condition True");
}
#else
void main()
{
printf("Condition False");
}
#endif
Output:

Condition True

Explanation:

5 is non zero number so #if condition is true.

Example 2b

#include<stdio.h>
#if 0
void main()
{
printf("Condition True");
}
#else
void main()
{
printf("Condition False");
}
#endif
Output:

Condition False
Explanation:

Since the value is 0, #if condition is false and statements in #else is executed.

Note : This C program contains more than one main()

Example 3

#include<stdio.h>
#define var 10
void main()
{
#if var
printf("Welcome To C World");
#else
printf("Thank you! Try Again");
#endif
}
Output:

Welcome To C World.

Explanation:

Macro constant var will be replaced 10. Since 10 is non-zero number so #if part will execute.

5.2.5 Miscellaneous Directive


There are two miscellaneous preprocessor directives and they are

(a) #undef

(b) #pragma

#undef Directive

Directive #undef is used to undefine any macro constants except global identifiers. It is useful when we want to
redefine any macro constants.
Syntax

#undef macro template

Example Program

#include<stdio.h>
#define ABC 25
#ifdef ABC
#undef ABC
#define ABC 50
#else
#define ABC 100
#endif
void main()
{
printf("%d",ABC);
}
Output

50

Explanation

Since macro constant ABC has already defined, #ifdef condition is true and the Directive #undef will undefine
the macro constant ABC. However, the statement #define ABC 50 will again define the macro ABC.
#pragma Directive

It has two types:

1. #pragma startup and


2. #pragma exit

#pragma startup: It allows a function to be called before the main program (i.e before the program execution).

#pragma exit: It allows a function to be called after the main program (i.e at the end of the program
termination).
Syntax: startup pragma

#pragma startup <function_name> [priority]

 startup pragma allow the program to specify function(s) that should be called upon program startup

 Function is called before main().

Syntax: exit pragma

#pragma exit <function_name> [priority]

 exit pragma allow the program to specify function(s) that should be called just before the program
terminates through _exit.

 Function is called after main().

Priority
 0 = Highest priority
 0-63 = Used by C libraries
 64 = First available user priority
 100 = Default priority
 255 = Lowest priority
The optional priority parameter is an integer in the range from 64 to 255.
Example:

#include <stdio.h>
void fun1(); //function Declaration
void fun2(); //function Declaration
#pragma startup fun1
#pragma exit fun2
void main( )
{
printf ( "\nI am Inside main" ) ;
}
void fun1( )
{
printf ( "\ni am before main" ) ;
}
void fun2( )
{
printf ( "\ni am after main" ) ;
}
Explanantion

Here the fun1 will be called before the execution and fun2 will be called after the main program.

Output

i am before main

i am inside main

i am after main

You might also like