Structures in C++ Programming
Structures in C++ Programming
BSE 1
Joddat Fatima
1
joddat.fatima@gmail.com
Department of C&SE
Bahria University Islamabad
INTRODUCTIONS
2
STRUCTURE
A structure can be considered as an array with elements of varying size.
A structure’s elements do not have to be the same size. Because of this each
element of a structure must be explicitly specified and is given a tag instead of
a numerical index.
To access an element, one must know the starting address of the structure and
the relative offset of that element from the beginning of the structure.
The elements of a structure are arranged in the memory in the same order as
they are defined in the struct definition.
3
SYNTAX
Definition of a structure:
struct <struct-type>
{
<type> <identifier_list>; Each identifier
<type> <identifier_list>; defines a member
... of the structure.
} ;
Example:
struct Date
The “Date” structure
{
int day; has 3 members,
int month;
int year;
day, month & year.
4
} ;
EXAMPLES
Example:
struct StudentInfo
{ The “StudentInfo”
int Id;
int age; structure has 4 members
char Gender; of different types.
double CGA;
};
Example:
struct StudentGrade
{ The “StudentGrade”
char Name[15]; structure has 5
char Course[9];
int Lab[5]; members of
int Homework[3];
int Exam[2];
different array types. 5
};
EXAMPLES
Example:
struct BankAccount
{
char Name[15]; The “BankAcount”
int AcountNo[10]; structure has simple,
double balance;
Date Birthday;
array and structure
}; types as members.
Example:
struct StudentRecord
{
char Name[15]; The “StudentRecord”
int Id;
char Dept[5]; structure has 4
6
char Gender; members.
};
DECLARING STRUCT VARIABLES
struct motor p, q, r;
Declares and sets aside storage for three variables – p, q, and r – each of
type struct motor
7
ACCESSING MEMBERS OF A STRUCT
Let
struct motor p;
struct motor q[10];
Then
Let
struct motor *p;
Then
This construct is so widely used that a special notation was invented, i.e.,
p->member, where p is a pointer to the structure 9
OPERATIONS ON STRUCT
Copy/assign
struct motor p, q;
p = q;
Get address
struct motor p;
struct motor *s
s = &p;
Access members
p.volts;
s -> amps;
10
OPERATIONS ON STRUCT (CONTINUED)
Remember:–
Passing an argument by value is an instance of copying or
assignment
Passing a return value from a function to the caller is an
instance of copying or assignment
E.g,:–
struct motor f(struct motor g) {
struct motor h = g;
...;
return h;
}
“If a large structure is to be passed to a function, it is generally 11
more efficient to pass a pointer than to copy the whole structure”
STRUCT BASICS
Name Name
Student1 Id Gender Id Gender Student2
Dept Dept
13
EX. 2: STRUCT BASICS
14
ARRAY TO STRUCTURES
15
POINTERS TO STRUCTURE
16