Top Banner

of 44

C-Programming-Class 5

May 30, 2018

Download

Documents

jack_harish
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 8/14/2019 C-Programming-Class 5

    1/44

    1

    Session 05

    Structures

  • 8/14/2019 C-Programming-Class 5

    2/44

    2

    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.

  • 8/14/2019 C-Programming-Class 5

    3/44

    3

    Session Topics

    Structure declaration Nested structure initialization

    Arrays and structures

    Functions and structures

    Union

  • 8/14/2019 C-Programming-Class 5

    4/44

    4

    What are Structures?

    A structure in C is a collection of variables which contains related items ofsimilar 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 orfields.

    We may require that the date of birth of persons be handled

    So far, we knew the method of doing this as declaring three integervariables such as

    int day, month, year;

    int birth_day, birth_month, birth_year;

    However, we may require in situations that we handle different types ofdates, such as date of joining job, date of graduation, date of getting lastpromotion, etc.

    Clearly each of the above dates involve three components, day, month andyear.

  • 8/14/2019 C-Programming-Class 5

    5/44

  • 8/14/2019 C-Programming-Class 5

    6/44

    6

    Structure InitializationA structure can be initialized in much the same

    way as we initialize the array elements.

    struct employee{

    char name[10];

    int salary;

    int id;

    };

    struct employee{

    char name[10];

    int salary;

    int id;

    }a={John,10000,56};

    Method I

    Struct employee a={John,10000,56};

    Method II

    Consider the

    structure below

  • 8/14/2019 C-Programming-Class 5

    7/44

    7

    Structure Initialization

    struct employee

    {

    char name[10];

    int salary;

    int id;

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

    Here only the variableb isinitialized and variable a is notinitialized.

    struct employee

    {

    char name[10];

    int salary;

    int id;

    }a={John,10000,56},

    b={Rama,15000,58};

    After

    rectific

    ation

  • 8/14/2019 C-Programming-Class 5

    8/44

    8

    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];

    int salary;

    int id;

    }a={John,10000,56};

    By specifying a.name we can accessthe name John.Similarly, the salary

    can be accessed by using a.id

    Ex:printf(%d\n,a.id);

  • 8/14/2019 C-Programming-Class 5

    9/44

    9

    Size of a structure

    struct employee

    {

    int age;

    char name[10];

    double salary;

    }a;

    2000 03 04 13 14 21

    age

    4 bytes

    name

    10 bytes

    salary

    8 bytes

    Total Size=4 + 10 + 8

    =22 bytes

    Base Address

  • 8/14/2019 C-Programming-Class 5

    10/44

    10

    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 datatype 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.

  • 8/14/2019 C-Programming-Class 5

    11/44

    11

    Structure Padding

    struct employee

    {

    int age;

    char name[10];

    double salary;

    }a;

    age

    4 bytes

    Slack name

    10 bytesSlack salary

    8 bytes

    00Base Address

    08 16 24

    Total Size=8 + 16 + 8

    =32 bytes

    32

  • 8/14/2019 C-Programming-Class 5

    12/44

    12

    Differences between Arrays & Structures

    Arrays are used to

    represent a group o

    objects of the same datatype.

    Ex:int arr[10];

    It is derived from a basic

    data type and is called as aderived data type.

    Structures are used where

    related data items o

    dissimilar data types butlogically related items are

    grouped together.

    It is a user defined

    composite data type andcalled User define data

    type.

    Arrays Structures

  • 8/14/2019 C-Programming-Class 5

    13/44

    13

    An Array of Structures

    To declare an array of structures, it is mandatory to define astructure and then declare an array variable of that type.

    struct employee

    {

    int age;

    char name[10];

    double salary;

    };

    Definition of

    employee structure

    Declaration with

    initialization

    struct employee a[3]

    {

    {John,10000,24},

    {Peter,20000,25},

    {Rama,12000,26}

    };

  • 8/14/2019 C-Programming-Class 5

    14/44

    14

    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{

    int age;

    char name[10];

    double salary;

    }a,b;

    struct employee1{

    int age;

    char name[10];

    double salary;

    }c,d;a=b;

    b=a;

    c=d;

    d=c;

    a=c;

    b=d;

    c=a;

    d=b;

  • 8/14/2019 C-Programming-Class 5

    15/44

    15

    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!=b;

    a.member1 == b.member2;

    a.member1 != b.member2;

  • 8/14/2019 C-Programming-Class 5

    16/44

    16

    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

    {

    char name[10];

    int reg_no;

    int marks1;

    int marks1;

    };

    struct subject

    {

    int marks1;

    int marks1;

    };

    The two members marks1 and

    marks2 can be a substructure.

  • 8/14/2019 C-Programming-Class 5

    17/44

    17

    Structures within structures

    struct student{

    char name[10];

    int reg_no;struct subject marks;

    };

    This substructure can be a member of another structure

    as shown below.

  • 8/14/2019 C-Programming-Class 5

    18/44

    18

    Passing Structures to Functions

    Structure information can be passed to afunction 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.

  • 8/14/2019 C-Programming-Class 5

    19/44

    19

    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);

    }

    void funct(int age,float *salary)

    {

    if(age>=30)

    *salary=20000;}

    Call by

    Value

    Call by

    Referenc

    e

  • 8/14/2019 C-Programming-Class 5

    20/44

  • 8/14/2019 C-Programming-Class 5

    21/44

    21

    Passing structures to functions

    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.

    The address of the structure

    is passed as an argument to

    the called function.

    There is no need of transferof data to the called function

    using the return statement

    due to the mechanism o

    pass by reference.

    Pass by Value Pass by Reference

  • 8/14/2019 C-Programming-Class 5

    22/44

    22

    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.

  • 8/14/2019 C-Programming-Class 5

    23/44

  • 8/14/2019 C-Programming-Class 5

    24/44

    24

    Bit-fields:Syntax

    struct tag_name

    {

    data_type identifier1:bit_length;

    data_type identifier2:bit_length;

    };

    KeywordName of

    thestructure

    data_typeif of type

    int

    identifier1are the

    names of thebit-fields

    bit_length isthe no. ofbits used

  • 8/14/2019 C-Programming-Class 5

    25/44

    25

    Bit-fields:Example

    struct student

    {char name[10];

    unsigned age : 2;

    unsigned roll_no :7;unsigned branch:3;

    };

  • 8/14/2019 C-Programming-Class 5

    26/44

  • 8/14/2019 C-Programming-Class 5

    27/44

    27

    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 declaredstatic.

    No field can be longer than 32 bits.

    It is not possible to declare an array of bit-fields.

  • 8/14/2019 C-Programming-Class 5

    28/44

    28

    Structure Pointers

    A pointer pointing to a structure is called as

    aStructure Pointer.

    C provides an operator->called arrowoperator to refer to the structure elements.

    To access the structure elements using a

    pointer,the -> is used.

  • 8/14/2019 C-Programming-Class 5

    29/44

    29

    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);

    }

  • 8/14/2019 C-Programming-Class 5

    30/44

    30

    Uses of Structures

    Structures are used to represent complex datastructures.

    Can be used to pass arguments so as to minimizethe number of functions arguments.

    When more than one data has to be returned fromthe function, then structures can be used.

    Used in applications in database management.

  • 8/14/2019 C-Programming-Class 5

    31/44

  • 8/14/2019 C-Programming-Class 5

    32/44

    32

    Unions: Syntax

    union tag_name

    {

    data_type member1;data_type member2;

    .

    .

    }variables;

    Keyword Name ofthe union

    List ofvariables

    It can be

    of anybasic data

    type

    Membersor

    attributes

  • 8/14/2019 C-Programming-Class 5

    33/44

    33

    Unions:An Example

    union example

    {

    int i;

    double d;

    char c;

    };

    union example x;

  • 8/14/2019 C-Programming-Class 5

    34/44

    34

    Unions:Memory Allocation

    union example

    {

    int i;

    double d;

    char c;

    };

    1000 1001 1002 10071006100510041003

    8 bytes

    c

    i

    d

  • 8/14/2019 C-Programming-Class 5

    35/44

    35

    Unions:Memory Allocation

    In unions,every member begins at an offset 0.

    The storage space allocated for an union is the size of itslargest member.

    The value of only one member can be stored at any instantof time.

    The number of bytes used for the storage space must beatleast enough to hold the largest member.

    Since all the bytes share the same memory,modificationsof one member will affect the other members.It is theresponsibility of the programmer to store and retrieve theappropriate data using various members.

  • 8/14/2019 C-Programming-Class 5

    36/44

    36

    Differences between Structures & Unions

    The keyword struct is used todefine a structure.

    Memory will be allocated foreach member.

    Each member is assigned itsown unique storage area.

    Individual members can beaccessed at a time.

    Several members of a structure

    can be initialized at once.

    The keyword union is used todefine a union.

    The memory allocated is thesize of the member that

    occupies largest space. Memory allocated is shared by

    individual members of union.

    Only one member can beaccessed at a time.

    Only the first member of aunion can be initialized.

    Structure Union

  • 8/14/2019 C-Programming-Class 5

    37/44

    37

    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;

    };

  • 8/14/2019 C-Programming-Class 5

    38/44

  • 8/14/2019 C-Programming-Class 5

    39/44

    39

    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 = 6GREEN = 4BLUE = 5

    Enumeration: An Example

  • 8/14/2019 C-Programming-Class 5

    40/44

    40

    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.

  • 8/14/2019 C-Programming-Class 5

    41/44

    41

    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

    typedeftype new_name;

    Example : typedef unsigned short int USHORT;typedef unsigned long int ULONG;

  • 8/14/2019 C-Programming-Class 5

    42/44

    42

    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.

  • 8/14/2019 C-Programming-Class 5

    43/44

    43

    Summary

    A structure in C is a collection of variables whichcontains related items of similar and/or dissimilar datatypes but logically related items.

    A member of a structure can be accessed by specifying

    the variable name followed by the . operator which inturn followed by the member name.

    A member of a structure that is composed only ofspecified number of bits is called asBit-field.

    A pointer pointing to a structure is called as aStructurePointer.

    An enumeration is a set of named integer constants.

  • 8/14/2019 C-Programming-Class 5

    44/44

    Thank You!