15742_structure n union

Upload: kunal-sharma

Post on 06-Apr-2018

213 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 15742_structure n Union

    1/41

    Structure

    Group of data items of different data

    types held together in a single unit.

  • 8/3/2019 15742_structure n Union

    2/41

    Declaring a Structure

    struct sname

    {

    type var1;type var2;

    type var3;

    .

    .

    type varN;

    };

    struct is a keyword to define a structure.

    sname is the name given to the structure data type.

    type is a built-in data type.

    var1,var2,var3,..,varN are elements of structure

    being defined.

    Structure template

    sname is called tag makes it possible to declare other

    variable of the same structure type without having to

    rewrite the template itself. Its a type name.tag is

    optional.

  • 8/3/2019 15742_structure n Union

    3/41

    Eg to store information of an employee, our structure

    declaration may look like as shown overleaf

    struct employee_type

    {

    int code;char name[20];

    int dept_code;

    float salary;};

    No variable has been associated with this structure

    No memory is set aside for this structure.

  • 8/3/2019 15742_structure n Union

    4/41

    Declaring Variables of the Structure Type

    Declares a variable employee of type employee_type

    At this point, the memory is set aside for the structure variableemployee.

    We can also declare variable(s) of structure type alongwith the structure declaration.

    struct employee_type employee;

    struct employee_type

    {int code;

    char name[20];

    int dept_code;

    float salary;

    }employee

  • 8/3/2019 15742_structure n Union

    5/41

    Consider the declarations to understand how the elements

    of the structure variables are stored in memory

    struct example_type

    {

    char var1;

    int var2;

    float var3;

    double var4;};

    struct example_type sample1;

    Note: all members are stored in contiguous memory location in order in which they aredeclared.

  • 8/3/2019 15742_structure n Union

    6/41

    How the elements of the structure variables are

    stored in memory

    1197

    1198

    1199

    1200

    12011202

    1203

    1204

    1205

    1206

    1207

    1208

    1209

    1210

    1211

    var 1

    var 2

    var 4

    var 3

  • 8/3/2019 15742_structure n Union

    7/41

  • 8/3/2019 15742_structure n Union

    8/41

    Accessing Structure Elements

    Elements are accessed using dot operator.

    It provides a powerful and clear way to refer to an

    individual element.Syntax: sname.vname

    sname is structure variable name.

    vname is name of the element of the structure.Eg: the element of the structure variable student

    can be accessed as

    student.rollno,student.name,student.age,student.height

  • 8/3/2019 15742_structure n Union

    9/41

    Entering Data into StructuresVoid main()

    {

    struct employee_type{

    int code;

    char name[25];

    char dept[15];

    float salary;

    };

    struct employee_type employee;

    printf(\nEnter employee code:\n);

    scanf(%d,&code);

    printf(\nEnter name:\n);

    gets(employee.name);

    printf(\nEnter employees dept:\n);

    gets(employee.dept);

    printf(\nEnter employees salary:\n);

    scanf(%f,&employee.salary);

    continue

    printf(\n\nParticulars of emp as entered by user\n);

    printf(\nEmployees code:%d,employee.code);

    printf(\nEmployees name:%s, employee.name);

    printf(\nEmployees dept:%s,employee.dept);

    Printf(\nEmployees sal:%f,employee.salary);

    continue

  • 8/3/2019 15742_structure n Union

    10/41

    Use of Assignment Statement for Structures

    Value of one structure variable can be assigned to

    another variable of the same type using simple

    assignment statement.if student1 and student2

    are structure variable of type student_type,thenstudent2=student1;

    Assigns value of structure variable student1 to

    student2

    Simple assignment cannot be used this way for

    arrays.

  • 8/3/2019 15742_structure n Union

    11/41

    WAP to copy structure elements

    from one object to another object#include#include

    #include

    Void main()

    {

    Struct disk

    {

    Char name[15];

    Float type;

    Int price;

    };

    clrscr();

  • 8/3/2019 15742_structure n Union

    12/41

    struct disk d1={sony,1.44,20};

    struct disk d2,d3;

    strcpy(d2.name,d1.name);

    d2.type=d1.type;

    d2.price=d1.price;d3=d2;

    printf(%s %g %d,d1.name,d1.type,d1.price);

    printf(%s %g %d,d2.name,d2.type,d2.price);printf(%s %g %d,d3.name,d3.type,d3.price);

    getch();

    }

  • 8/3/2019 15742_structure n Union

    13/41

    Difference b/w array and structure

  • 8/3/2019 15742_structure n Union

    14/41

    Array of Structures

    If we wish to process a list of values of structuretype,then we need an array of such structures.

  • 8/3/2019 15742_structure n Union

    15/41

    Declaring an Array of Structures

    struct employee_type{

    int code;

    char name[25];char dept[15];

    float salary;

    };

    struct employee_type employee[50];

  • 8/3/2019 15742_structure n Union

    16/41

    Accessing elements an array of structures

    Individual elements of a structure in an array of

    structure are accessed by referring to

    structure variable name.

    1. Followed by subscript.

    2. Followed by dot operator.

    3. Ending with structure element desired.

    Suppose we want to access salary of 7th

    employee,we can do so by writing

    employee[6].salary

  • 8/3/2019 15742_structure n Union

    17/41

    To ind avg marks o 3 subjects o 5

    studentsVoid main()

    {

    Struct student

    {

    int subject1;

    int subject2;

    int subject3;}

    };

  • 8/3/2019 15742_structure n Union

    18/41

    int i,total=0;

    float av;

    struct student st[20];for(i=0;i

  • 8/3/2019 15742_structure n Union

    19/41

    Array within Structure

    when a array declared and processed within a

    structure, then it is called array within

    strucure

    struct name

    {

    char fname[10];char lname[10];

    };

  • 8/3/2019 15742_structure n Union

    20/41

    Nested Structure

    Structure can be embedded within another

    structure,i.e when a structure declared and

    processed within another structure,then it is

    called nesting of structure

  • 8/3/2019 15742_structure n Union

    21/41

    SyntaxStruct tag1

    {

    member elements-1;

    ..

    member element-m;

    };

    struct tag2

    {

    struct tag1 v1;};

    Struct tag2 v2;

  • 8/3/2019 15742_structure n Union

    22/41

    ExampleVoid main()

    {

    stuct name

    {

    char fname[10];

    char lname[10];

    };

    Struct bdate

    {

    int day;int month;

    int year;

    };

  • 8/3/2019 15742_structure n Union

    23/41

    struct data

    {

    struct name n;

    struct bdate b;

    };

    struct data d;

    printf(enter name);

    scanf(%s %s,d.n.fname,d.n.lname);

    printf(enter birth date);scanf(%d %d %d,d.b.day,d.b.month,d.b.year);

    printf(name %s %s, d.n.fname,d.n.lname);

    printf(DOB

    %d %d %d,d.b.day,d.b.month,d.b.year);

  • 8/3/2019 15742_structure n Union

    24/41

    Structure and Function

    The relationship of structure with the function

    can be viewed as:-1. Passing Structures to a function..

  • 8/3/2019 15742_structure n Union

    25/41

    Passing Structure to a Function

    Similar to passing array of variable,structure can be

    passed to a function as argument

    Syntax:Data-type func-name(struct-variable); /*actual argument*/

  • 8/3/2019 15742_structure n Union

    26/41

    Read and display student grade by

    using structure with functionstruct student{

    int rn;

    char name[20];

    char grade;

    }s;

    main()

    {

    printf(\nEnter rollno,name and grade of student:\n);

    scanf(%d %s %c,&s.rn,s.name,&s.grade);

    display(s);

    getch();

    }

    display(struct student m)

    {

    printf(\nRollno is %d,m.rn);

    printf(\n Name is %s,m.name);

    printf(\n Grade is: %c,m.grade);

    }

  • 8/3/2019 15742_structure n Union

    27/41

    Passing of structure variables by value to a function

    struct date

    {

    int day;

    int month;

    int year;

    };

    void print_date(struct date);

    void main()

    {

    struct date d={10,12,1997};

    print_date(d);

    }

    void print_date(struct date a)

    {

    printf(\nDate in format %d %d %d,a.day,a.month,a.year);

    }

  • 8/3/2019 15742_structure n Union

    28/41

    Passing of structure variables by reference to a function

    struct date

    {

    int day;

    int month;

    int year;

    };

    main(){

    struct date d;

    void get_date(struct date *);

    printf(Enter date in the format:\n);

    get_date(&d);

    printf(\nDate entered by you %d %d %d,d.day,d.month,d.year);

    }

    void get_date(struct date *a)

    { scanf(%d %d %d,&a->day,&a->month,a->year);

  • 8/3/2019 15742_structure n Union

    29/41

    Structures and pointers

    struct date { int month, day, year;

    };

    struct date todays_date, *date_pointer;date_pointer = &todays_date;

    (*date_pointer).day = 21;

    (*date_pointer).year = 1985;(*date_pointer).month = 07;

    ++(*date_pointer).month;

    if((*date_pointer).month == 08 ) ......

  • 8/3/2019 15742_structure n Union

    30/41

    Str pointers

    Pointers to structures are so often used in C

    that a special operator exists. The structure

    pointer operator, the ->, permits expressions

    that would otherwise be written as,

    (*x).yto be more clearly expressed as

    x->ymaking the if statement from above

    program

    if( date_pointer->month == 08 ) .....

  • 8/3/2019 15742_structure n Union

    31/41

    * Program to illustrate structure pointers */ #include

    main()

    { struct date

    { int month, day, year;

    }; struct date today, *date_ptr;

    date_ptr = &today;

    date_ptr->month = 9;

    date_ptr->day = 25;

    date_ptr->year = 1983; printf("Todays date is %d/%d/%d.\n", date_ptr->month, date_ptr->day, date_ptr-

    >year % 100); }

  • 8/3/2019 15742_structure n Union

    32/41

    bitfields

    Both C and C++ allow integer members to be stored into memory spaces

    smaller than the compiler would ordinarily allow. These space-saving

    structure members are called bit fields, and their width in bits can be

    explicitly declared. Bit fields are used in programs that must force a data

    structure to correspond to a fixed hardware representation and are

    unlikely to be portable.

    The syntax for declaring a bit field is as follows:

    >>-type_specifier--+------------+--:--constant_expression--;--->< '-declarator-'

    A bit field declaration contains a type specifier followed by an optional

    declarator, a colon, a constant integer expression that indicates the field

    width in bits, and a semicolon. A bit field declaration may not use either of

    the type qualifiers, const or volatile

  • 8/3/2019 15742_structure n Union

    33/41

    Alignment of Bit Fields

    If a series of bit fields does not add up to the size of an int, padding can take place.

    The amount of padding is determined by the alignment characteristics of the

    members of the structure.

    The following example demonstrates padding, and is valid for all implementations.

    Suppose that an int occupies 4 bytes. The example declares the identifier kitchen

    to be of type struct on_off:

    struct on_off { unsigned light : 1; unsigned toaster : 1; int count; /* 4 bytes */

    unsigned ac : 4; unsigned : 4; unsigned clock : 1; unsigned : 0; unsigned flag : 1; }

    kitchen ; The structure kitchen contains eight members totalling 16 bytes

  • 8/3/2019 15742_structure n Union

    34/41

    Member Name StorageOccupied

    light 1 bit

    toaster 1 bit

    (padding -- 30 bits) To the next int boundary

    count The size of an int (4 bytes)

    ac 4 bit

    (unnamed field) 4 bits

    clock 1 bit

    (padding -- 23 bits)

    To the next int boundary (unnamed field)

    flag 1 bit (padding -- 31 bits) To the next int boundary

  • 8/3/2019 15742_structure n Union

    35/41

    UNION

    A union is variable that declares a set of

    multiple variable (called members or elements

    having different data-type)sharing the same

    memory area

    The union require the bytes that are equal to

    the number of bytes required for the largest

    member.

  • 8/3/2019 15742_structure n Union

    36/41

    It is declared in two ways:-

    Union union-tag

    {Data-type-1 member-element-1;

    --------------------------------------

    Data-type-n meber-element-2;

    }v1,v2,....vn;

    Union union-tag

    {

    Data-type-1 member-element-1;

    --------------------------------------

    Data-type-n meber-element-2;

    };

    Union tag-name v1,v2,....vn;

  • 8/3/2019 15742_structure n Union

    37/41

    Union item

    {

    int m;

    float x;char c;

    } code;

    This declare a variable code of type union item.

  • 8/3/2019 15742_structure n Union

    38/41

    WAP to find the size of union and

    number of bytes reserved for it

    main()

    {

    union result{

    int marks;

    char grade;};

  • 8/3/2019 15742_structure n Union

    39/41

    struct res

    {

    char name[15];

    int age;

    union result r1;

    }data;

    printf(size of union %d,sizeof(data.r1));

    printf(size of structure %d,sizeof(data));

    }

  • 8/3/2019 15742_structure n Union

    40/41

    Union

    Union:

    Union is similar as structure. The major distinction between

    them in terms of storage.

    In structure each member has its own storage locationwhereas all the members of union uses the same location.

    The union may contain many members of different data type

    it can handle only one member at a time union can be declaredusing the keyword union.

  • 8/3/2019 15742_structure n Union

    41/41