Sie sind auf Seite 1von 44

Session 05

Structures

1
Session Objectives

• To learn the concepts of structures and unions.


• To know the handling of arrays, pointers, and functions
involving structures.
• To understand the concepts of unions and enumerated data
types.

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;

char name[10]; int id;

int salary; }a={“John”,10000,56};

int id;
Method II
};
Struct employee a={“John”,10000,56};

6
Structure Initialization

struct employee struct employee


{ {
char name[10]; char name[10];
r n
int salary; f te tio int salary;
A ica
c tif
int id; re int id;
}a,b={“John”,10000,56}; }a={“John”,10000,56},
b={“Rama”,15000,58};

Here only the variable b is


initialized and variable a is not
initialized.

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

age name salary


4 bytes 10 bytes 8 bytes

9
Size of a structure

•In a structure,each member must have an address divisible by the


highest data type present in the structure.
•In such cases, extra bytes are padded at the end of each member
so that the address of each member is divisible by the highest data
type present in the structure.
•These extra bytes do not contain any valid information and are
called as Slack Bytes. This concept is called as Structure
Padding.

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

age Slack name


Slack salary
4 bytes 10 bytes
8 bytes

11
Differences between Arrays & Structures

Arrays Structures

• Arrays are used to • Structures are used where


represent a group of related data items of
objects of the same data dissimilar data types but
type. logically related items are
Ex:int arr[10]; grouped together.
• It is derived from a basic • It is a user defined
data type and is called as a composite data type and
derived data type. called User define data
type.

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.

Definition of Declaration with


employee structure initialization
struct employee struct employee a[3]
{ {
int age; {“John”,10000,24},
char name[10]; {“Peter”,20000,25},
double salary; {“Rama”,12000,26}
}; };

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

struct employee struct employee1


{ {
int age; int age;
char name[10]; char name[10];
double salary; double salary;
}a,b; }c,d;
a=b; a=c; c=d; c=a;
b=a; b=d; d=c; d=b;

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.

struct student The two members marks1 and


{ marks2 can be a substructure.
char name[10]; struct subject
int reg_no; {
int marks1; int marks1;
int marks1; int marks1;
}; };

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

Structure information can be passed to a


function in three different ways.They are:
2) Passing structure members to functions.
3) Passing structures to functions using Pass by
value.
4) Passing structures to functions using Pass by
reference.

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

• Consider an application where all the members of a structure


are of data type int and have the values from 0 to 16 in order.
• In such cases,too much of memory is wasted.To conserve
memory in such cases the concept of bit-fields is used.
• Structures can also be declared with members consisting of
specified number of bits.Such a member is called a bit-field.
• A group of several bits can be packed together using a
structure.

22
Bit-fields

• A member of a structure that is composed only of


specified number of bits is called as Bit-field.
• Using bit-fields we can access one or more bits.
• Bit-field can provide greater control over the
structure's storage allocation and allow a close knit
packing of information in memory.

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

Data can be densely packed using bit-fields.


Devices that transmit encoded status information
can be viewed and manipulated using bitwise
operators.
Certain encrypted routines sometimes access the
bits within a byte.
The programs will be more structured and can be
used for easy debugging.

26
Restrictions on Bit-fields

• Address of a bit-field cannot be accessed.


• scanf( ) cannot be used to read temporary
variables and then assign it to the bit-fields.
• Pointers cannot be used to access bit-fields.
• Bit-fields cannot be declared static.
• No field can be longer than 32 bits.
• It is not possible to declare an array of bit-fields.

27
Structure Pointers

• A pointer pointing to a structure is called as


a Structure Pointer.
• C provides an operator ‘->’ called arrow
operator to refer to the structure elements.
• To access the structure elements using a
pointer,the -> is used.

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

Structures are used to represent complex data


structures.
Can be used to pass arguments so as to minimize
the number of functions arguments.
When more than one data has to be returned from
the function, then structures can be used.
Used in applications in database management.

30
Unions

• Union is a concept derived from structures.


• Unions are memory locations that contains
members of various data types.
• In unions,all members share the same
storage space and so at any instant, a union
can handle only one item.

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

In unions,every member begins at an offset 0.


The storage space allocated for an union is the size of its
largest member.
The value of only one member can be stored at any instant
of time.
The number of bytes used for the storage space must be
atleast enough to hold the largest member.
Since all the bytes share the same memory,modifications
of one member will affect the other members.It is the
responsibility of the programmer to store and retrieve the
appropriate data using various members.

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

An enumeration is a set of named integer constants.


Enumerations are defined much like structures.
The keyword enum signals the start of an enumeration type.
Syntax:

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

It helps to make machine-dependent programs


more portable.
If we define our own type name for each machine-
dependent data type used by the program,then
only the typedef statements have to be changed
when compiling for a new environment.

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

Das könnte Ihnen auch gefallen