Lecture 4 Structures in C++

You might also like

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

Structures in C++

Lecture 4
Lecture Outline
1. Concept of a structure
2. Structure definition
3. How to declare structures
4. How to initialize structures
5. How to access structures
6. Arrays and Structures
7. Pointers and Structures
8. Structures and Functions
Concept of a Structure
• We have already dealt with arrays. Arrays are used to store similar
type of data. Have you ever thought if there is any way to
store dissimilar data?

• The answer is yes. We use structures to store different types of


data.

• For example, you are a student. Your name is a string and your
phone number and reg_no are integers. So, here name, address and
phone number are those different types of data. Here, structure
comes in the picture.
Concept of a Structure (2)
• Recall that elements of arrays must all be of the same type

scores
scores: : 85
85 79
79 92
92 57
57 68
68 80
80 . .. .. .
0 1 2 3 4 5 98 99

• In some situations, we wish to group elements of different types

employee
employee R.
R.Jones
Jones 123
123Elm
Elm 6/12/55
6/12/55 $14.75
$14.75

4
Structure Definition
• Recall that an array is a collection of data items, all having the SAME
DATA TYPE and accessed using a common name and an INTEGER INDEX
into the collection.

• A struct is also a collection of data items, except with a struct the data
items can have DIFFERENT DATA TYPES, and the individual fields within
the struct are ACCESSED BY NAME instead of an integer index. These
data items are called MEMBERS

• Structs are very powerful for BUNDLING TOGETHER data items that
collectively describe a thing, or are in some other way related to each
other.
Structure Definition (2)
• A structure is a user-defined data type in C++. A structure creates a data
type that can be used to group items of possibly different types into a
single type.

• A structure is a collection of related data items stored in one place and can
be referenced by more than one names.  Usually these data items are
different basic data types.  Therefore, the number of bytes required to
store them may also vary.

• It is very useful construct used in data structure, although in C++,


many struct constructs has been replaced by class construct
How to create a structure?
• In order to use a structure, we must first declare a structure template/skeleton .  The
variables in a structure are called elements or members.

• The ‘struct’ keyword is used to create a structure. The general syntax to create a
structure is as shown below:

struct  structureName{
data-type  member1;
data-type  member2;
.
.
.
data-type  memberN;
};
How to create a structure?(2)
• For example, to store and process • Here, struct is a keyword that
a student’s record with the tells the compiler that a
elements id_num , name and age, structure template is being
we can declare the following declared and student is a tag
structure. that identifies its data
structure.
struct student { • Tag is not a variable; it is a label
string id_num; for the structure’s template.
string name;
int age; • Note that there is a semicolon
}; after the closing curly brace.
How to create a structure?(3)
• A structure tags simply a label for the structure’s template but you
name the structure tag using the same rules for naming variables

• Compiler will not reserve memory for a structure until you declare
a structure variable same as you would declare normal variables
such as int or float.

• Declaring structure variables can be done in any of the following


ways (by referring to the previous example):
How to create a structure?(4)|Structure Variables
Method(2)
struct student {
string id_num;
Method (1)
string name;
struct student {
int age;
string id_num; };
string name; • Based on no. 2 version, then in main
int age; program we can declare the structure
something like this:
};  studno_1, studno_2;

• struct    student    studno_1, studno_2;
How to create a structure?
|Structure Variables(2)
• In the above two cases, two structure variables, 
studno_1 and studno_2, are declared

• Each structure variable has 3 elements that is 2 string variables and


an integer variable.

• In (1) the structure variables is declared immediately after the


closing brace in the structure declaration whereas in (2) they are
declared as student in the main of the program. 
#include<iostream> cout<<"\nEnter student idno ";
using namespace std; cin>>studno1.id_num;
cout<<"\nEnter your age";
struct student { cin>>studno1.age;
string id_num;
string name; cout << "\n\nHello " << studno1.name <<" reg no "
int age; << studno1.id_num<< ". How are you?\n ";
};
cout << "\nCongratulations on reaching the age of
" << studno1.age<< ".\n";
int main(){
struct student studno1;
return 0;
}
cout<<"Enter student name ";
cin>>studno1.name;
How to initialize structure members?
• Structure members cannot be initialized with declaration.
For example the following C++ program fails in compilation.

struct Point {
int x = 0; // COMPILER ERROR: cannot initialize members here
int y = 0; // COMPILER ERROR: cannot initialize members here
};
How to initialize structure members?(2)
• Structure members can be initialized using curly braces ‘{}’. For
example, the following is a valid initialization.

struct Point {
int x, y;
};

int main() {
// A valid initialization. member x gets value 0 and y
// gets value 1. The order of declaration is followed.
struct Point p1 = {0, 1};
}
#include <iostream>
using namespace std; How to access
struct Point {
structure elements?
int x, y;
};
• Structure members are
accessed using the dot (.)
int main() { operator.
struct Point p1 = { 0, 1 };

// Accessing members of point p1


p1.x = 20;
cout << "x = " << p1.x << ", y = " << p1.y;

return 0;
} //Output: x = 20, y = 1
Structure Example(2)| declaration, initialization and
accessing structure elements
Structure Example(3)
| Copying Structure Elements
• We can also copy two
structures at one go. We
just have to write p1 = p2
and that's it. By writing
this, all the elements of
p1 will get copied to p2.
Array of Structures

• We can also make an array of structures. In the previous example


we stored the data of 3 students. Now suppose we need to store
the data of 100 such children. Declaring 100 separate variables of
the structure is definitely not a good option. For that, we need to
create an array of structures.

• Let's see an example for 5 students.


Array of Structures(2)
Array of Structures(2)…..
Array of Structures(3)

• Here we created an array named stud having 5 elements of


structure student. Each of the element stores the information of a
student. For example, stud[0] stores the information of the first
student, stud[1] for the second and so on.
#include <iostream>
Array of Structures(4)
using namespace std;

struct Point { // Access array members


int x, y; arr[0].x = 10;
}; arr[0].y = 20;

int main() { cout << arr[0].x << " " << arr[0].y;
// Create an array of structures return 0;
struct Point arr[10]; }

• Output: 10 20
Pointers to Structures

• Like we have pointers to int, char and other data-types, we also have
pointers pointing to structures. These pointers are called structure pointers.
Below is h0w we define a structure pointer

• struct structure_name{
    data-type member-1;
    data-type member-2;
    data-type member-N;
};

int main(){
    struct  structure_name *ptr;
}
• Like primitive types, we can have a
pointer to a structure. If we have a Pointers to Structures (2)
pointer to structure, members are
accessed using arrow ( -> ) operator
instead of the dot (.) operator.
// p2 is a pointer to structure p1
struct Point* p2 = &p1;
#include <iostream>
using namespace std; // Accessing structure members using
structure pointer
struct Point {
int x, y;
}; cout << p2->x << " " << p2->y;
return 0;
int main() { }
struct Point p1 = { 1, 2 }; Output: 1 2
Pointers to Structures(3)
Pointers to Structures(4)

• struct student *ptr; - We declared 'ptr' as a pointer to the


structure student.

• ptr = &stud; - We made our pointer ptr to point to the structure


variable stud. Thus, 'ptr' now stores the address of the structure
variable 'stud'.

• cout << ptr->name << ptr->roll_no << endl; - We use -> operator to


access the members of a structure using a pointer to that
structure.
Structure to Function

• 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

• In this, we pass structure variable as an argument to a function.


Let's see an example to make it clearer.
Structure to Function|Passing by Value
Structure to Function| Passing by Value (2)
• In this 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 structure variable.
Structure to Function| Passing by Reference
• In passing by reference, the address of a structure variable is
passed to a function.
Structure to Function| Passing by Reference(2)

• This case is similar to the previous one, the only difference is that
this time, we are passing the address of the structure variable to
the function.

• While declaring the function, we passed the pointer of the copy 'st'
of the structure variable 's' in its parameter. Since 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 the members of the pointer
using -> sign as discussed before.

You might also like