C-Programming-Class 5
C-Programming-Class 5
Structures
1
Session Objectives
2
Session Topics
• Structure declaration
• Nested structure initialization
• Arrays and structures
• Functions and structures
• Union
3
What are Structures?
• A structure in C is a collection of variables which contains related items of
similar and/or dissimilar data types but logically related items.
• So in a structure, the individual elements can be integer, character, floating
point or arrays.
• The constituents of a structure are called its members or fields.
• We may require that the date of birth of persons be handled
– So far, we knew the method of doing this as declaring three integer
variables such as
int day, month, year;
int birth_day, birth_month, birth_year;
– However, we may require in situations that we handle different types of
dates, such as date of joining job, date of graduation, date of getting last
promotion, etc.
– Clearly each of the above dates involve three components, day, month and
year.
4
Declaration of Structure Variables
Keyword Name of
the
struct tag_name structure
{
Example data_type member_1; Declaration
terminated by
data_type member_2; a semicolon
struct employee
……
{
……
char name[10];
List of
int salary; }structure-variables; one or
int id; more
}emp1; variables
5
Structure Initialization
A structure can be initialized in much the same
way as we initialize the array elements.
Method I
Consider the struct employee
structure below {
char name[10];
struct employee
{ int salary;
int id;
Method II
};
Struct employee a={“John”,10000,56};
6
Structure Initialization
7
Accessing the members of a structure
A member of a structure can be accessed by specifying the variable name
followed by the ‘.’ operator which in turn followed by the member name.
variable.member
Consider the structure definition and initialization below:
struct employee
By specifying a.name we can access
{ the name John.Similarly, the salary
char name[10]; can be accessed by using a.id
int salary; Ex: printf(“%d\n”,a.id);
int id;
}a={“John”,10000,56};
8
Size of a structure
struct employee
{ Total Size=4 + 10 + 8
int age; =22 bytes
char name[10];
double salary;
}a;
Base Address
2000 03 04 13 14 21
9
Size of a structure
10
Structure Padding
struct employee
{ Total Size=8 + 16 + 8
int age; =32 bytes
char name[10];
double salary;
}a;
Base Address
00 08 16 24 32
11
Differences between Arrays & Structures
Arrays Structures
12
An Array of Structures
To declare an array of structures, it is mandatory to define a
structure and then declare an array variable of that type.
13
Copying of Structure Variables
• Copying of two structure variables is achieved using assignment
operator.
• Note: One structure variable can be assigned to another structure
variable of the same type.
• Consider the following two structures
14
Comparison of two structure variables
Copying of two structure variables of same type is allowed.
Comparing of two structure variables of same type or dissimilar type is
not allowed.
struct employee
a==b;
{
a!=b;
int age;
a.member1 == b.member2;
char name[10];
a.member1 != b.member2;
double salary;
}a,b;
15
Structures within structures
The nesting of structures is permitted in C language.
The structure can be used as a member of another structure.
Consider the following structures.
16
Structures within structures
This substructure can be a member of another structure
as shown below.
struct student
{
char name[10];
int reg_no;
struct subject marks;
};
17
Passing Structures to Functions
18
Passing Structure members to functions
Each member of the structure is passed as an argument and the
corresponding formal parameters are then treated like ordinary
variables.
Each member of the structure can be passed either using “Pass by
Value” OR “Pass by Reference”.
Call by
Value
void main() void funct(int age,float *salary)
{ {
…….; if(age>=30)
………; *salary=20000;
}
funct(a.age,&a.salary); Call by
} Referenc
e
19
Passing Structure members to functions
Disadvantages:
• If all the members of the structure are passed, the number
of arguments will be more.
• It is not applicable for slightly large structures.
20
Passing structures to functions
Pass by Value Pass by Reference
• The entire structure is passed • The address of the structure
as a parameter. is passed as an argument to
• If the result has to be returned the called function.
to the calling function it can • There is no need of transfer
be achieved using return of data to the called function
statement and the entire using the return statement
structure has to be returned. due to the mechanism of
pass by reference.
21
Bit-fields
22
Bit-fields
23
Bit-fields:Syntax
Keyword Name of
the
structure
struct tag_name
{
data_type identifier1:bit_length;
data_type identifier2:bit_length;
}; data_type identifier1 bit_length is
if of type are the the no. of
names of the bits used
int bit-fields
24
Bit-fields:Example
struct student
{
char name[10];
unsigned age : 2;
unsigned roll_no :7;
unsigned branch:3;
};
25
Advantages of Bit-fields
26
Restrictions on Bit-fields
27
Structure Pointers
28
Structure Pointers:An Example
main()
{
struct book
{
char name[10];
int num;
};
static struct book b1={“Embedded Systems”,100};
struct book *ptr;
ptr=&b1;
printf(“%s %d\n”,b1.name,b1.num);
printf(“%s %d\n”,ptr->name,ptr->num);
}
29
Uses of Structures
30
Unions
31
Unions: Syntax
Keyword
Name of
union tag_name the union
{
It can be
of any
data_type member1;
basic data data_type member2;
type
………. Members
or
………. attributes
}variables;
List of
variables
32
Unions:An Example
union example
{
int i;
double d;
char c;
};
union example x;
33
Unions:Memory Allocation
8 bytes
union example
1000 1001 1002 1003 1004 1005 1006 1007
{
int i;
double d;
c
char c;
i
};
d
34
Unions:Memory Allocation
35
Differences between Structures & Unions
Structure Union
• The keyword struct is used to • The keyword union is used to
define a structure. define a union.
• Memory will be allocated for • The memory allocated is the
each member. size of the member that
• Each member is assigned its occupies largest space.
own unique storage area. • Memory allocated is shared by
• Individual members can be individual members of union.
accessed at a time. • Only one member can be
• Several members of a structure accessed at a time.
can be initialized at once. • Only the first member of a
union can be initialized.
36
Enumerated Data Type
enum colours
{ red;
green;
blue;
};
37
Enumerated Data Type
• enum is the abbreviation for ENUMERATE, and we can use this keyword to
declare and initialize a sequence of integer constants.
• Here, colours is the name given to the set of constants - the name is optional.
Now, if you don't assign a value to a constant, the default value for the first
one in the list - RED in our case, has the value of 0. The rest of the undefined
constants have a value 1 more than the one before, so in our example, GREEN
is 1 and BLUE is 2.
• But you can assign values if you wanted to:
enum colours { RED=1, GREEN=6, BLUE };
Now RED=1, GREEN=6 and BLUE=7.
The main advantage of enum is that if you don't initialize your constants, each
one would have a unique value.
The first would be zero and the rest would then count upwards.
38
Enumeration: An Example
main()
{
enum {RED=5, YELLOW, GREEN=4, BLUE};
printf("RED = %d\n", RED);
printf("YELLOW = %d\n", YELLOW);
printf("GREEN = %d\n", GREEN);
printf("BLUE = %d\n", BLUE);
}
Output:
RED = 5
YELLOW = 6
GREEN = 4
BLUE = 5
39
enum Variables
Enumerated constants are integers, so programs with statements like x
= RED; would still compile.
But you can also create your own enumerated data types, for example,
colours is now considered an enumerated data type. So you can say:
enum colours background;
This declares a variable called background, which is of the enumerated
data type, colours.
Declaring enumerated data types can also be done after the list of
constants, like this:
enum colours {BLACK, WHITE}, bg, fg;
This makes bg and fg variables of the enumerated data type, colors.
Statements like bg = BLACK; can now be used.
40
typedef
• We can define new data type names using the keyword
typedef.
• We are not creating a new data type, but rather defining a
new name for an existing data type.
• typedef statements could be placed anywhere in your
program – A good programming practice is to group them
all before main.
• The general form of the typedef statement is
typedef type new_name;
• Example : typedef unsigned short int USHORT;
typedef unsigned long int ULONG;
41
Advantages of typedef
42
Summary
• A structure in C is a collection of variables which
contains related items of similar and/or dissimilar data
types but logically related items.
• A member of a structure can be accessed by specifying
the variable name followed by the ‘.’ operator which in
turn followed by the member name.
• A member of a structure that is composed only of
specified number of bits is called as Bit-field.
• A pointer pointing to a structure is called as a Structure
Pointer.
• An enumeration is a set of named integer constants.
43
Thank You!
44