C-programming-class 5

  • Uploaded by: jack_harish
  • 0
  • 0
  • May 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View C-programming-class 5 as PDF for free.

More details

  • Words: 2,401
  • Pages: 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

Example struct employee {

struct tag_name { data_type member_1; data_type member_2; …… ……

char name[10]; int salary; int id; }emp1;

}structure-variables;

Name of the structure Declaration terminated by a semicolon

List of one or more variables

5

Structure Initialization A structure can be initialized in much the same way as we initialize the array elements. Consider the structure below struct employee { char name[10]; int salary; int id; };

Method I struct employee { char name[10]; int salary; int id; }a={“John”,10000,56};

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

6

Structure Initialization struct employee

struct employee

{

{ char name[10]; int salary; int id;

n r te tio f A ica tif c re

}a,b={“John”,10000,56};

char name[10]; int salary; int id; }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

char name[10];

By specifying a.name we can access the name John.Similarly, the salary 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

{

=22 bytes

int age; 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

{

=32 bytes

int age; char name[10]; double salary; }a; Base Address

00

age 4 bytes

08

Slack

16

name 10 bytes

24

Slack

32

salary 8 bytes 11

Differences between Arrays & Structures Arrays • Arrays are used to represent a group of objects of the same data type. Ex:int arr[10]; • It is derived from a basic data type and is called as a derived data type.

Structures • Structures are used where related data items of dissimilar data types but logically related items are grouped together. • It is a user defined composite data type and 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 employee structure

Declaration with 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

{

{

}a,b;

int age;

int age;

char name[10];

char name[10];

double salary;

double salary;

a=b;

a=c;

b=a;

b=d;

}c,d;

c=d;

c=a;

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 { int age; char name[10]; double salary;

a==b; a!=b; a.member1 == b.member2; a.member1 != b.member2;

}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”. void main() { …….; ………; funct(a.age,&a.salary); }

Call by Value

void funct(int age,float *salary) { if(age>=30) *salary=20000; } 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 • The entire structure is passed as a parameter. • If the result has to be returned to the calling function it can be achieved using return statement and the entire structure has to be returned.

Pass by Reference • The address of the structure is passed as an argument to the called function. • There is no need of transfer of data to the called function using the return statement 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 if of type int

identifier1 are the names of the bit-fields

bit_length is the no. of bits used 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 the union

union tag_name { It can be of any basic data type

data_type member1; data_type member2; ………. ………. }variables;

Members or attributes

List of variables 32

Unions:An Example union example { int i; double d; char c; }; union example x; 33

Unions:Memory Allocation 8 bytes 1000

1001

1002

1003

1004

1005

1006

1007

union example { 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 • • • • •

The keyword struct is used to define a structure. Memory will be allocated for each member. Each member is assigned its own unique storage area. Individual members can be accessed at a time. Several members of a structure can be initialized at once.

Union • • • • •

The keyword union is used to define a union. The memory allocated is the size of the member that occupies largest space. Memory allocated is shared by individual members of union. Only one member can be accessed at a time. 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 machinedependent 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

Related Documents

5-5
July 2020 70
5-5
December 2019 109
5-5
May 2020 85
5
October 2019 39
5
November 2019 51
5
June 2020 15