Structures
Lecture No 3
COMSATS Institute of
Information & Technology
2

Structures







Ordinary variables can hold one piece of
information.
Arrays can hold a number of pieces of
information of the same data type.
Quite often we deal with entities that are
collection of dissimilar data types.
Want to store data about a book.
Want to store its name (a string), its price (a
float) and number of pages in it (an int).
Object Oriented Programming
3

Structures
C

and C++ support data structures that
can store combinations of character,
integer floating point and enumerated
type data. They are called structs.
 In general, we can say a structure is a
collection of different types of data.

Object Oriented Programming
4

„C++‟ implementation of
Structure
The keyword „struct‟ is used for creating a
structure.
 Syntax:
struct structure-name
{
datatype1 varname1;
datatype1 varname2;
datatype1 varname3;
};
creating the object of structure:
Struct structure-name var1, var2, var3;


Object Oriented Programming
5

Declaration
struct list {
int roll;
char name[10];
float marks;
};
struct list a , b , c;
It is equivalent to:
struct list {
int roll;
char name[10];
float marks;
}a, b, c;

Object Oriented Programming
6

Reserves Space
Declaring Structures (struct)

Does Not Reserve Space
struct my_example
{
int label;
char letter;
char name[20];

struct my_example
{
int label;
char letter;
char name[20];
} mystruct ;

};

/* The name "my_example" is
called a structure tag

*/

Object Oriented Programming
7

Accessing Struct Members


Individual members of a struct variable may be
accessed using the structure member operator (the
dot, “.” member access operator)
mystruct.letter ;



Or , if a pointer to the struct has been declared and
initialized
Some_name *myptr = &mystruct ;
by using the structure pointer operator (the “->“):
myptr -> letter ;
which could also be written as:
(*myptr).letter ;
Object Oriented Programming
8

Accessing structure elements


. (dot operator) is used to access individual structure element
e.g.
struct list
{
int roll;
char name[10];
float marks;
};
struct list a , b , c;
a.roll––is the integer element of structure a.
a.name––is char array element of structure a.
b.marks––is a float element of structure b.
a.marks––is a float element of structure b.
scanf( “%d”, &b.roll); this statement can accept an integer roll of structure
from user. This is applied to all the elements of a structure.

Object Oriented Programming
9

Things to remember:


The closing brace in the structure type declaration must be
followed by a semicolon.



Structure type declaration does not tell the compiler to
reserve any space in memory. All a structure declaration
does is, it defines the „form‟ of the structure.



Usually structure type declaration appears at the top of the
source code file, before any variables or functions are
defined. In very large programs they are usually put in a
separate header file, and the file is included (using the
preprocessor directive #include) in whichever program we
want to use this structure type.

Object Oriented Programming
10

How Structure Elements are
Stored :

 Whatever

be the elements of a structure, they are
always stored in contiguous memory locations.
/*Memory map of structure elements*/
main()
{ struct book
{ char name;
float price;
int pages;
};
struct book b1 = {„B‟, 130.00, 550};
Object Oriented Programming
11

Output:

Object Oriented Programming
12

Array of Structures:
 To

store data of 100 books we would be
required to use 100 different structure
variables from b1 to b100,

A

better approach would be to use an
array of structures.

Object Oriented Programming
13

/* Usage of an array of structures */
main( )
{
struct book
{
char name ;
float price ;
int pages ;
};
struct book b[100] ;
int i ;
Object Oriented Programming
14

for ( i = 0 ; i <= 99 ; i++ )
{
cout << "nEnter name, price and pages " ;
cin >> b[i].name, b[i].price, b[i].pages;
}
for ( i = 0 ; i <= 99 ; i++ )
cout << b[i].name, b[i].price, b[i].pages <<endl;
}

Object Oriented Programming
15

Passing structure to a function:
Struct Test
{
int marks;
Char grade;
};
void show(Test p);
void main()
{
Test t;
cout <<“Enter marks:”
cin>>t.marks;
cout <<“Enter grade:”
cin>>t.grade;
show(t);
getch();
}

Object Oriented Programming
16

void show(Test p)
{
cout<<“Marks:”<<p.marks<<endl;
cout<<“Grade:”<<p.grade<<endl;
}

Object Oriented Programming
17

Structure Pointers:
 The

way we can have a pointer pointing
to an int, or a pointer pointing to a char,
similarly we can have a pointer pointing
to a struct.

Object Oriented Programming
18

struct Book
{
char author[30];
Int pages;
Int price
}
Void main()
{
Book rec, *ptr;
ptr = &rec;
cout<<“Enter author name:”;
cin.get(ptr->author, 30);

Object Oriented Programming
19

cout<<“Enter pages:”;
cin>>ptr->pages;
cout<<“Author:”<<ptr->author<<endl;
cout<<“Pages:”<<ptr->pages<<endl;
}

Object Oriented Programming
20

Structures within Structures
struct date
{

int day, month, year;

};
struct employrec
{
char name[20[;
char id[20];
float salary;
struct date hiredate;
};
struct employrec employees;

To access the field day of structure type date,
employees.hiredate.day = 10;
Object Oriented Programming
21

User Defined Data Types
(typedef)


The C language provides a facility called typedef
for creating synonyms for previously defined data
type names. For example, the declaration:
typedef int Length;



makes the name Length a synonym (or alias) for
the data type int.
The data “type” name Length can now be used in
declarations in exactly the same way that the
data type int can be used:
Length a, b, len ;
Length numbers[10] ;
Object Oriented Programming
22

Typedef & Struct
 Often,

typedef is used in combination with struct to
declare a synonym (or an alias) for a structure:
typedef struct
{
int label ;
char letter;
char name[20] ;
} Some_name ;
Some_name mystruct ;
*/

/* Define a structure */

/* The "alias" is Some_name */
/* Create a struct variable
Object Oriented Programming
23

Enumeration


Enumeration is essentially a method of creating a
numbered list. It allows the user to assign names to
numbers which can then be used as indices in an
array



Enumeration is a user-defined data type. It is defined using
the keyword enum and the syntax is:
enum tag_name {name_0, …, name_n} ;



The tag_name is not used directly. The names in the braces
are symbolic constants that take on integer values from
zero through n. As an example, the statement:
enum colors { red, yellow, green } ;
creates three constants. red is assigned the value 0, yellow
is assigned 1 and green is assigned 2.



Object Oriented Programming
24

Enumeration
/* This program uses enumerated data types to
access the elements of an array */
#include <stdio.h>
int main( )
{
int March[5][7]={{0,0,1,2,3,4,5},{6,7,8,9,10,11,12},
{13,14,15,16,17,18,19},{20,21,22,23,24,25,26},
{27,28,29,30,31,0,0}};
enum days {Sunday, Monday, Tuesday,
Wednesday, Thursday, Friday, Saturday};
Object Oriented Programming
25

Enumeration
enum week {week_one, week_two,
week_three,
week_four, week_five};
printf ("Monday the third week "
"of March is March %dn",
March [week_three] [Monday] );

}
Object Oriented Programming

Oop lec 3(structures)

  • 1.
    Structures Lecture No 3 COMSATSInstitute of Information & Technology
  • 2.
    2 Structures      Ordinary variables canhold one piece of information. Arrays can hold a number of pieces of information of the same data type. Quite often we deal with entities that are collection of dissimilar data types. Want to store data about a book. Want to store its name (a string), its price (a float) and number of pages in it (an int). Object Oriented Programming
  • 3.
    3 Structures C and C++ supportdata structures that can store combinations of character, integer floating point and enumerated type data. They are called structs.  In general, we can say a structure is a collection of different types of data. Object Oriented Programming
  • 4.
    4 „C++‟ implementation of Structure Thekeyword „struct‟ is used for creating a structure.  Syntax: struct structure-name { datatype1 varname1; datatype1 varname2; datatype1 varname3; }; creating the object of structure: Struct structure-name var1, var2, var3;  Object Oriented Programming
  • 5.
    5 Declaration struct list { introll; char name[10]; float marks; }; struct list a , b , c; It is equivalent to: struct list { int roll; char name[10]; float marks; }a, b, c; Object Oriented Programming
  • 6.
    6 Reserves Space Declaring Structures(struct) Does Not Reserve Space struct my_example { int label; char letter; char name[20]; struct my_example { int label; char letter; char name[20]; } mystruct ; }; /* The name "my_example" is called a structure tag */ Object Oriented Programming
  • 7.
    7 Accessing Struct Members  Individualmembers of a struct variable may be accessed using the structure member operator (the dot, “.” member access operator) mystruct.letter ;  Or , if a pointer to the struct has been declared and initialized Some_name *myptr = &mystruct ; by using the structure pointer operator (the “->“): myptr -> letter ; which could also be written as: (*myptr).letter ; Object Oriented Programming
  • 8.
    8 Accessing structure elements  .(dot operator) is used to access individual structure element e.g. struct list { int roll; char name[10]; float marks; }; struct list a , b , c; a.roll––is the integer element of structure a. a.name––is char array element of structure a. b.marks––is a float element of structure b. a.marks––is a float element of structure b. scanf( “%d”, &b.roll); this statement can accept an integer roll of structure from user. This is applied to all the elements of a structure. Object Oriented Programming
  • 9.
    9 Things to remember:  Theclosing brace in the structure type declaration must be followed by a semicolon.  Structure type declaration does not tell the compiler to reserve any space in memory. All a structure declaration does is, it defines the „form‟ of the structure.  Usually structure type declaration appears at the top of the source code file, before any variables or functions are defined. In very large programs they are usually put in a separate header file, and the file is included (using the preprocessor directive #include) in whichever program we want to use this structure type. Object Oriented Programming
  • 10.
    10 How Structure Elementsare Stored :  Whatever be the elements of a structure, they are always stored in contiguous memory locations. /*Memory map of structure elements*/ main() { struct book { char name; float price; int pages; }; struct book b1 = {„B‟, 130.00, 550}; Object Oriented Programming
  • 11.
  • 12.
    12 Array of Structures: To store data of 100 books we would be required to use 100 different structure variables from b1 to b100, A better approach would be to use an array of structures. Object Oriented Programming
  • 13.
    13 /* Usage ofan array of structures */ main( ) { struct book { char name ; float price ; int pages ; }; struct book b[100] ; int i ; Object Oriented Programming
  • 14.
    14 for ( i= 0 ; i <= 99 ; i++ ) { cout << "nEnter name, price and pages " ; cin >> b[i].name, b[i].price, b[i].pages; } for ( i = 0 ; i <= 99 ; i++ ) cout << b[i].name, b[i].price, b[i].pages <<endl; } Object Oriented Programming
  • 15.
    15 Passing structure toa function: Struct Test { int marks; Char grade; }; void show(Test p); void main() { Test t; cout <<“Enter marks:” cin>>t.marks; cout <<“Enter grade:” cin>>t.grade; show(t); getch(); } Object Oriented Programming
  • 16.
  • 17.
    17 Structure Pointers:  The waywe can have a pointer pointing to an int, or a pointer pointing to a char, similarly we can have a pointer pointing to a struct. Object Oriented Programming
  • 18.
    18 struct Book { char author[30]; Intpages; Int price } Void main() { Book rec, *ptr; ptr = &rec; cout<<“Enter author name:”; cin.get(ptr->author, 30); Object Oriented Programming
  • 19.
  • 20.
    20 Structures within Structures structdate { int day, month, year; }; struct employrec { char name[20[; char id[20]; float salary; struct date hiredate; }; struct employrec employees; To access the field day of structure type date, employees.hiredate.day = 10; Object Oriented Programming
  • 21.
    21 User Defined DataTypes (typedef)  The C language provides a facility called typedef for creating synonyms for previously defined data type names. For example, the declaration: typedef int Length;  makes the name Length a synonym (or alias) for the data type int. The data “type” name Length can now be used in declarations in exactly the same way that the data type int can be used: Length a, b, len ; Length numbers[10] ; Object Oriented Programming
  • 22.
    22 Typedef & Struct Often, typedef is used in combination with struct to declare a synonym (or an alias) for a structure: typedef struct { int label ; char letter; char name[20] ; } Some_name ; Some_name mystruct ; */ /* Define a structure */ /* The "alias" is Some_name */ /* Create a struct variable Object Oriented Programming
  • 23.
    23 Enumeration  Enumeration is essentiallya method of creating a numbered list. It allows the user to assign names to numbers which can then be used as indices in an array  Enumeration is a user-defined data type. It is defined using the keyword enum and the syntax is: enum tag_name {name_0, …, name_n} ;  The tag_name is not used directly. The names in the braces are symbolic constants that take on integer values from zero through n. As an example, the statement: enum colors { red, yellow, green } ; creates three constants. red is assigned the value 0, yellow is assigned 1 and green is assigned 2.  Object Oriented Programming
  • 24.
    24 Enumeration /* This programuses enumerated data types to access the elements of an array */ #include <stdio.h> int main( ) { int March[5][7]={{0,0,1,2,3,4,5},{6,7,8,9,10,11,12}, {13,14,15,16,17,18,19},{20,21,22,23,24,25,26}, {27,28,29,30,31,0,0}}; enum days {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; Object Oriented Programming
  • 25.
    25 Enumeration enum week {week_one,week_two, week_three, week_four, week_five}; printf ("Monday the third week " "of March is March %dn", March [week_three] [Monday] ); } Object Oriented Programming