Chapter-10
Structures and Unions
Copyright © 2016 McGraw Hill Education, All Rights Reserved.
PROPRIETARY MATERIAL © 2016 The McGraw Hill Education, Inc. All rights reserved. No part of this PowerPoint slide may be displayed, reproduced
or distributed in any form or by any means, without the prior written permission of the publisher, or used beyond the limited distribution to teachers and
educators permitted by McGraw Hill for their individual course preparation. If you are a student using this PowerPoint slide, you are using it without
permission.
Introduction
• Structure is a mechanism for packing data of different types.
• It is a convenient tool for handling a group of logically related data
items.
• Its concept is analogous to a ‘record’.
• Examples:
• student : name, roll_number, marks
• time : seconds, minutes, hours
• date : day, month, year
• city : name, country, population
• address : name, door-number, street, city
• customer : name, telephone, city, category
Defining a structure
• General format/template of a structure definition:
struct tag_name
{
data_type member1;
data_type member1;
--- ---
--- ---
};
• Example:
struct book_bank
{
char title[20]; //array of 20 characters
char author[15]; //array of 15 characters
int pages; //integer
float price; //float
};
Arrays vs Structures
• Both arrays and structures are structured data types.
• They differ as follows:-
• An array is a collection of related data elements of same type.
Structure can have elements of different types.
• An array is derived data type whereas a structure is a
programmer-defined one.
• An array behaves like a built-in data type. All we have to do is to
declare an array variable and use it. But in case of a structure,
first we have to design and declare a data structure before the
variables of that type are declared and used.
Declaring Structure Variables
• Structure variable declaration includes:-
• The keyword struct.
• The structure tag name.
• List of variable names separated by commas.
• A terminating semicolon.
• Example: struct book_bank book1, book2, book3;
//declares book1, book2, book3 as variable of type struct boon_bank.
struct book_bank{
char title[20];
char author[15];
int pages;
float price;
};
struct book_bank book1, book2, book3;
• The following declaration is valid:-
struct book_bank //tag name is optional
{
char title[20];
char author[15];
int pages;
float price;
} book1, book2, book3;
Accessing structure members
• The link between a member and a variable is established using the
member operator ‘.’ also known as ‘dot operator’ or ‘period
operator’.
• Example: book1.price; //variable representing price of book1
• Assigning values to members of book1 can be done as:
• strcpy(book1.title, “BASIC”);
• strcpy(book1.author, “Balagurusamy”);
• book1.pages = 250;
• book1.price = 120.50;
• or
• scanf(“%s\n”,book1.title);
• scanf(“%d\n”, &book1.pages);
Fig. 10.1 Defining and accessing
structure members
Structure Initialization
• Compile time initialization:-
main(){
struct{
int weight;
float height;
} student = {60, 180.75};
----
}
main(){
struct st_record{
int weight;
float height;
};
struct st_record st_student1 = {60, 180.75};
struct st_record st_student2 = {65, 170.75};
----
}
struct st_record{
int weight;
float height;
} student1 = {60, 180.75};
main(){
struct st_record st_student2 = {65, 170.75};
----
----
}
Rules for Initializing Structures
• C does not permit initialization of individual structure members
within the template.
• Initialization must be done only in the declaration of the actual
variables.
• The order of values enclosed in braces must match order of
members in the structure definition.
• It is permitted to have partial initialization. Uninitialized members
should be only at the end of the list.
• Uninitialized default values:
• Zero for integer and floating point numbers.
• ‘\0’ for characters and strings.
Copying and Compare
• Two variables of the same structure type can be copied:-
• person1 = person2;
• Comparisons such as- person1 == person2 not permitted.
• Comparing members individually is permitted.
Fig. 10.2 Comparing and copying structure variables
Word Boundaries and Slack Bytes
0 1 2 3
<-- char --> Slack byte <------------- int ------------- >
Operations on Individual Members
• if(student1.number == 111)
student1.marks += 10.00;
• float sum = student1.marks + student2.marks;
• student2.marks *= 0.5;
• student1.number++;
• ++student1.number;
ARRAYS OF STRUCTURES
• struct class student[100];
• //defines array called student, consists of 100 elements. Each element is defined to be of the type
struct class.
struct marks{
int subject1;
int subject2;
int subject3;
};
main(){
struct marks student[3] = {{45,68,81}, {75,53,69}, {57,36,71}};
}
• student[0].subject1 = 45;
• ------
Fig. 10.3 The array student inside memory
Fig. 10.4 Arrays of structures: Illustration of
subscripted structure variables
Array within Structures
struct marks{
int number;
int subject[3];
} student[2];
(Contd.)
Fig. 10.5 Use of subscripted members arrays in structures
Structures within Structures
• C permits nesting of structures.
• union salary{
char name;
char department;
int basic_pay;
int dearness_allowance;
int house_allowance;
int city_allowance;
} employee;
• struct salary{
char name;
char department;
struct{
int dearness_allowance;
int house_allowance;
int city_allowance;
} allowance;
} employee;
Structures and Functions
• Three methods by which the values of a structure can be transferred
from one function to another-
• Pass each member of the structure as an actual argument of the
function call. Actual arguments are then treated independently
like ordinary variables.
• Second method is passing a copy of the entire structure to the
called function.
• Third method is to use pointers to pass the structure as an
argument. The address location of the structure is passed to the
called function.
Passing copy of structure
• The general format of sending a copy of a structure to the
called function is:
• function_name(structure_variable_name);
• The called function takes the following form:-
data_type function_name(struct_type st_name)
{
…..
return(expression);
}
Important Points
• The called function must be declared for its type,
appropriate to the data type it is expected to return. e.g. if
it is returning a copy of the entire structure, then it must
be declared as struct with an appropriate tag name.
• The structure variable used as the actual argument and
the corresponding formal argument in the called function
must be of the same struct type.
• When a function returns a structure, it must be assigned
to a structure of identical type in the calling function.
• The called function must be declared in the calling
function appropriately.
(Contd.)
Fig. 10.6 Using structure as a function parameter
UNIONS
• Unions follow the same syntax as structures.
• Major distinction is in terms of storage.
• In structures, each member has its own storage location,
whereas all the members of a union use the same
location.
• Although a union may contain many members of different
types, it can handle only one member at a time.
• Declare using keyword union as follows:
union item
{
int m;
float x;
char c;
} code;
Fig. 10.7 Sharing of a storage locating by union members
Type-Defined Structures
• The keyword typedef can be used to define structure as follows:
typedef struct
{
……
type member1;
type member2;
…..
…..
} type_name;
• type_name represents structure definition associated with it and
therefore, can be used to declare structure variable:-
• type_name variable1, variable2,….;
Pointers and Structures
• The name of arrays of structure variables stands for the address of its
zeroth element.
• Example:
struct inventory{
char name[30];
int number;
float price;
} product[2], *ptr;
• The above statement declares product as an array of two elements,
each of type struct inventory.
• ptr = product; //assign the address of zeroth element of product to ptr.
• Its members can be accessed using:
ptr -> name; // -> is called arrow operator
ptr -> number; // or member selection operator
ptr -> price