Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 40

Structures

Department of Computer Science,


Shifa Tameer-e-Millat University, Islamabad
Introducing Structures
 A structure is a collection of multiple data types that
can be referenced with single name.

 The data items in structure are called structure


members, elements, or fields.

 The difference between array and structure: is that


array must consists of a set of values of same data
type but on the other hand, structure may consists
of different data types.
Defining the Structure
• Structure definition tells how Syntax:
the structure is organized: it struct StructName
specifies what members the {
DataType1 Identifier1;
structure will contain. DataType2 Identifier2;
.
.
.
Syntax & Example  };

Example:

struct Product
{
int ID;
string name;
float price;
};
Structure Definition Syntax
Declaring a Structure variable
• Structure variable can be defined after the definition of a
structure. The syntax of the declaration is:

StructName Identifier;

Example:
part processor;
part keyboard;

• This declaration tells the compiler to allocate memory space


according to the elements of the structure.

• The structure variable processor and keyboard occupies 12


bytes in the memory. 4 bytes for modelnumber, 4 bytes for
Structure members in memory

4 Bytes
modelnumber

struct part
{ 4 Bytes
int partnumber
modelnumber;
int partnumber;
float cost; 4 Bytes
}; cost
Another way of Declaring a Structure variable
• You can also declare struct variables when you
define the struct. For example:
struct part
{
int modelnumber;
int partnumber;
float cost;
} part1;

 These statements define the struct named part and


also declare part1 to be a variable of type part.
Examples

struct employee struct student


{ {
string firstName; string firstName;
string lastName; string lastName;
string address; char courseGrade;
double salary; int Score;
int deptID; double CGPA;
};
} s1, s2;

employee e1;
Initializing Structure Variables
• The syntax of initializing structure is:

StructName struct_identifier = {Value1, Value2, …};


Structure Variable Initialization with Declaration
struct student
{
string firstName;
string lastName;
char courseGrade;
int marks;
};

void main( )
{
student BC022010= {“M”, “Umar”, ‘A’, 94} ;
}

Note: Values should be written in the same sequence in which


they are specified in structure definition.
Assigning Values to Structure Variables
• After creating structure variable, values to structure
members can be assigned using dot (.) operator

• The syntax is as follows:

student BC111017;

BC111017.firstName = “Muhammad”;
BC111017.lastName = “Umar”;
BC111017.courseGrade = ‘A’;
BC111017.marks = 93;
Assigning Values to Structure Variables
• After creating structure variable, values to structure
members can be assigned using cin.

• Output to screen using cout

student BC012311;

cin>>BC012311.firstName;
cin>>BC012311.lastName;
cin>>BC012311.courseGrade;
cin>>BC012311.marks ;
Assigning one Structure Variable to another
• A structure variable can be assigned to another
structure variable only if both are of same type

• A structure variable can be initialized by assigning


another structure variable to it by using the assignment
operator as follows:

Example:
studentType newStudent = {“John”, “Lee”, ‘A’, 99} ;

studentType student2 = newStudent;


Array of Structures
• An array can also be created of user-defined type such as: structure.

• An array of structure is a type of array in which each element


contains a complete structure.

struct Book
{
int ID;
int Pages;
float Price;
};

Book CUSTLibrary[100]; // declaration of array of structures

CUSTLibrary[0]
ID Pages Price
CUSTLibrary[1]
ID Pages Price
… CUSTLibrary[99]
ID Pages Price
Initialization of Array of Structures
struct Book
{
int ID;
int Pages;
float Price;
};
Book b[3]; // declaration of array of structures

• Initializing can be at the time of declaration


Book b[3] = {{1,275,70},{2,600,90},{3,786,100}};

• Or can be assigned values using cin:


cin>>b[0].ID ;
cin>>b[0].Pages;
cin>>b[0].Price;
Array as Member of Structures
• A structure may also contain arrays as members.

struct Student
{
int RollNo;
float Marks[3];
};

• Initialization can be done at time of declaration:

Student S = {1, {70.0, 90.0, 97.0} };


Array as Member of Structures
• Or it can be assigned values later in the program:
Student S;
S.RollNo = 1;
S.Marks[0] = 70.0;
S.Marks[1] = 90.0;
S.Marks[2] = 97.0;

• Or user can use cin to get input directly:


cin>>S.RollNo;
cin>>S.Marks[0];
cin>>S.Marks[1];
cin>>S.Marks[2];
Nested Structure
• A structure can be a member of another structure:
called nesting of structure
struct A
{
int x;
double y;
};

struct B
{ record
char ch; v1
A v1; ch x y
};

B record;
Initializing/Assigning to Nested Structure
struct A{ void main()
int x; {
float y; B record;
}; cin>>record.ch;
cin>>record.v2.x;
struct B{ cin>>record.v2.y;
char ch; }
A v2;
}; void main()
{
B record;
void main() record.ch = ‘S’;
{ record.v2.x = 100;
B record = {‘S’, {100, 3.6} }; record.v2.y = 3.6;
} }
Passing structures and array of structures to
functions by pointers

We can also pass a structure to a function.

There are two methods by which we can pass structures to


functions.
• Passing by Value
• Passing by Reference
Passing by Value
In this, we pass structure variable as an argument to a
function. Let's see an example to make it clearer.
struct student
{
int roll_no;
string name;
int phone_number;
};

void display(struct student st)


{
cout << "Roll no : " << st.roll_no << endl;
cout << "Name : " << st.name << endl;
cout << "Phone no : " << st.phone_number << endl;
st.phone_number=4343;;
}

int main(){
struct student s;
s.roll_no = 4;
s.name = "Ron";
s.phone_number = 888888;
display(s);
cout<<s.phone_number;
return 0;
Passing by Value
Passing by Value
• In the above example, we are printing roll number, name
and phone number of a student using a function. We first
declared a structure named student with roll_no, name
and phone number as its members and 's' as its variable.
Then we assigned the values of roll number, name and
phone number to the structure variable s. Just as we pass
any other variable to a function, we passed the structure
variable 's' to a function 'display'.
• Now, while defining the function, we passed a copy of the
variable 's' as its argument with 'struct student' written
before it because the variable which we have passed is of
type structure named student. Finally, in the function, we
printed the name, roll number and phone number of the
Passing by Reference
In passing by reference, the address of a structure variable is
passed to a function. In this, if we change the structure
variable which is inside the function, the original structure
variable which is used for calling the function changes. This
was not the case in calling by value.
struct student
{
int roll_no;
string name;
int phone_number;
};
void display(struct student &st)
{
cout << "Roll no : " << st.roll_no << endl;
cout << "Name : " << st.name << endl;
cout << "Phone no : " << st.phone_number << endl;
st.phone_number=4343;;
}
int main(){
struct student s;
s.roll_no = 4;
s.name = "Ron";
s.phone_number = 888888;
display(s);
cout<<s.phone_number;
return 0;
}
Passing by Reference
Passing by Reference
• This case is similar to the previous one, the only difference
is that this time, we are passing the address of the
If you do
structure not practice,
variable you don't
to the function. Whiledeserve
declaringto
thewin.
function, we passed the pointer of the copy 'st' of the
structure variable 's' in its parameter. Since-Andre Agassi
the pointer is
of a variable of type structure named student, we wrote
'struct student' before the name of the pointer in the
argument of the function. In the function , we accessed
If you do not practice, you don't deserve to pass.
the members of the pointer using -> sign as discussed
before.
• Try to change the value of the variables-Ghulam
inside theMustafa
function in both the cases and see the changes in the real
variables.
Class Exercises(1) – Find Errors
• Find errors:
struct
{
int x;
float y;
};

struct values
{
char name[20];
int age;
}
Class Exercises(2) – Find Errors
• Find errors:
struct TwoVals
{
int a,b;
};

int main()
{
TwoVals.a=10;
TwoVals.b=20;
}
Class Exercises(3) – Find Errors
• Find errors:
struct ThreeVals
{
int a,b,c;
};

int main()
{
ThreeVals vals={1,2,3};
cout<<vals<<endl;
return 0;
}
Class Exercises(4) – Find Errors
• Find errors:
struct names
{
char first[20];
char last[20];
};

int main()
{
names customer = {“Muhammad”, “Ali”};
cout<<names.first<<endl;
cout<<names.last<<endl;
return 0;
}
Class Exercises(5) – Find Errors
• Find errors:
struct TwoVals
{
int a=5;
int b=10;
};

int main()
{
TwoVals v;
cout<<v.a<<“”<<v.b;
return 0;
}
Class Exercise-6
• Define a structure called “car”. The member elements
of the car structure are:
• string Model;
• int Year;
• float Price

Create an array of 30 cars. Get input for all 30 cars


from the user. Then the program should display
complete information (Model, Year, Price) of those
cars only which are above 500000 in price.
Class Exercise-6
Class Exercise-7
• Write a program that implements the following using C++
struct. The program should finally displays the values stored
in a phone directory (for 10 people)

PhoneDirectory

Name PhoneNo Address

City Country
Class Exercise-7
Study After Pointer
Topic
Accessing Structures with Pointers
• Pointer variables can be used to point to structure
type variables too.
• The pointer variable should be of same type, for
example: structure type

struct Rectangle {
int width;
int height;
};

void main( )
{
Rectangle rect1={22,33};
Rectangle* rect1Ptr = &rect1;
}
Accessing Structures with Pointers
• How to access the structure members (using
pointer)?
– Use dereferencing operator (*) with dot (.) operator

struct Rectangle {
int width;
int height;
};

void main( )
{
Rectangle rect1={22,33};
Rectangle* rectPtr = &rect1;
cout<< (*rectPtr).width<<(*rectPtr).height;
}
Accessing Structures with Pointers
• Is there some easier way also?
– Use arrow operator ( -> )

struct Rectangle {
int width;
int height;
};

void main( )
{
Rectangle rect1={22,33};
Rectangle* rectPtr = &rect1;
cout<< rectPrt->width<<rectPrt->height;
}
Passing by Reference

You might also like