You are on page 1of 10

Chapter 3

C++ 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 roll_no are integers. So, here
name, address and phone number are those different types of data. Here, structure comes in
the picture.
A struct then is a collection of information of different data types (heterogeneous). The
fields of a struct are referred to as members.
NOTE

The word struct_name is a new data type. Data members may be any type, including
pointers, references, arrays, and other structures whose types do not have the same name as
struct_name. The compiler does not allocate memory with this format because we define
only a type and not a variable.
Structure data members cannot have the same type name as their enclosing structure, but
we can define pointers to the same structure type.
Defining a Structure
The syntax for structure is:
struct structure_name
{
data-type member-1;
data-type member-2;
data-type member-3;
data-type member-4;
};
In our case, let's name the structure as student. The members of the structure in our case are
name, roll_no and phone_number.
So, our structure will look like:

PP by Inst Dejene B FPII Page 1


struct student
{
int roll_no;
string name;
int phone_number;
};
Declaration of Structure Variable
Just as we declare variables of type int, char etc, we can declare variables of a structure as
well. Suppose we want to store the roll no, name and phone number of three students. For
this, we will define a structure named student (as declared above) and then declare three
variables, say p1, p2 and p3 (which will represent the three students respectively) of type
'student'. This declaration will be done in the main function.
struct student {
int roll_no;
string name;
int phone_number;
};
int main(){
struct student p1, p2, p3;
return 0;
}
We can also declare structure variables at the time of defining the structure as follows.
struct student
{
int roll_no;
sstring name;
int phone_number;
}p1, p2, p3;

Now, let's see how to enter the details of each student i.e. roll_no, name and phone number.
PP by Inst Dejene B FPII Page 2
Suppose we want to assign a roll number to the first student. For that, we need to access the
roll number of the first student. We do this by writing
p1.roll_no = 1;
This means that we use dot (.) to use variables in a structure. p1.roll_no can be understood
as roll_no of p1.
Now, let's store the details of all the three students.

#include <iostream>#include <cstring>


using namespace std;
int main(){
struct student{
int roll_no;
string name;
int phone_number;
};

struct student p1 = {1,"Brown",123443};


struct student p2, p3;
p2.roll_no = 2;
p2.name = "Sam";
p2.phone_number = 1234567822;
p3.roll_no = 3;
p3.name = "Addy";
p3.phone_number = 1234567844;

cout << "First Student" << endl;


cout << "roll no : " << p1.roll_no << endl;
cout << "name : " << p1.name << endl;
cout << "phone no : " << p1.phone_number << endl;
cout << "Second Student" << endl;
cout << "roll no : " << p2.roll_no << endl;
cout << "name : " << p2.name << endl;
cout << "phone no : " << p2.phone_number << endl;
cout << "Third Student" << endl;
cout << "roll no : " << p3.roll_no << endl;
cout << "name : " << p3.name << endl;
cout << "phone no : " << p3.phone_number << endl;
return 0;}
 struct student p1 = {1,"Brown",123443}; - This line is just to show that we can also
initialize a structure in this way.
 In the next line, we are just giving values to the variables and printing those.
 Structures use continuous memory locations

Initializing structure variables

PP by Inst Dejene B FPII Page 3


It is possible to give values to the structure members at the point of definition like the
following.
#include<iostream.h>
#include<conio.h>
const int NAME = 25;
const int ID = 11;
struct student
{
char name [NAME];
char id-num[ID];
int age;
}
int main ( ){
student stud1 = { “Alem “, “019/97”,25};//initialization
student stud2;
stud2= stud1;
cout<<name:”<<stud1.name:
cout<<\nID: “ << stud1. id_num;
cout”\n Copied data “ “<< endl;
cout<<”Name: “<< stud2. name;
cont<<”\nID: “<<stud2.id_num;
cout<<”\n Age:”<<stud2.age;
}
In this program, we initialized the name, id_num and age members of the student variable
type sud1. Note that we initialize values based on the order of the variables in the structure
specification of student, first for name, then for id, then age another feature in this program
is that we can use the assignment operator to assign the value of each member of stud1 to
the corresponding member of stud2. This type of assignment is possible only if the two
structure variables are the same type (in the above case, both are of same type student).
Another thing you should note in this program is the use of the global constant NAME and
ID. They can be used both in the structure and in main, and hence they are called global

PP by Inst Dejene B FPII Page 4


We can also make an array of structures. In the first example in structures, 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.
struct and Aggregate Operations
 Aggregate I/O is not allowed. I/O must be performed on a member by member
basis.
 Aggregate assignment is allowed. All data members (fields) are copied.
 Aggregate arithmetic is not allowed.
 Aggregate comparison is not allowed. Comparisons must be performed on a member
 by member basis.
 A struct is a valid return type for a value returning function.
Array of Structures

Let's see an example for 5 students.


#include <iostream>
#include <cstring>
using namespace std;
struct student
{
int roll_no;
string name;
int phone_number;
};

int main(){
struct student stud[5];
int i;
for(i=0; i<5; i++){ //taking values from user
cout << "Student " << i + 1 << endl;
cout << "Enter roll no" << endl;
cin >> stud[i].roll_no;
cout << "Enter name" << endl;
cin >> stud[i].name;
cout << "Enter phone number" << endl;
cin >> stud[i].phone_number;
}

PP by Inst Dejene B FPII Page 5


for(i=0; i<5; i++){ //printing values
cout << "Student " << i + 1 << endl;
cout << "Roll no : " << stud[i].roll_no << endl;
cout << "Name : " << stud[i].name << endl;
cout << "Phone no : " << stud[i].phone_number << endl;
}
return 0; }

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.

We can also copy two structures at one go.


#include <iostream>#include <cstring>
using namespace std;
struct student {
int roll_no;
string name;
int phone_number;
};
int main(){
struct student p1 = {1,"Brown",123443};
struct student p2;
p2 = p1;
cout << "roll no : " << p2.roll_no << endl;
cout << "name : " << p2.name << endl;
cout << "phone number : " << p2.phone_number << endl;
return 0;
}utput
We just have to write p1 = p2 and that's it. By writing this, all the elements of p1 will get
copied to p2.

PP by Inst Dejene B FPII Page 6


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. Now, how to define a pointer to a
structure? The answer is below:

struct structure_name
{ Expression What is evaluated Equivalent
data-type member-1;
data-type member-1; a.b Member b of variable a
data-type member-1;
data-type member-1; a->b Member b of variable pointed by a (*a).b
};
int main() *a.b Value pointed by member b of variable a *(a.b)
{
struct structure_name*ptr;
}

Let's see an example using structure pointer.

#include <iostream>#include <cstring>


using namespace std;
struct student{
string name;
int roll_no;

};

int main(){

struct student stud = {"Sam",1};


struct student *ptr;
ptr = &stud;

cout << stud.name << stud.roll_no << endl;


cout << ptr->name << ptr->roll_no << endl;
return 0;
}put
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'.This is the same which we do while defining a
pointer to any other variable.

PP by Inst Dejene B FPII Page 7


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
Passing by Value

In this, we pass structure variable as an argument to a function. Let's see an example to


make it clearer.

#include <iostream>
#include <cstring>
using namespace std;
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;
}

int main(){
struct student s;
s.roll_no = 4;
s.name = "Ron";
s.phone_number = 888888;
display(s);
return 0;
}ut
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'.

PP by Inst Dejene B FPII Page 8


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.

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.

#include <iostream>
#include <cstring>
using namespace std;
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;
}

int main(){
struct student s;
s.roll_no = 4;
s.name = "Ron";
s.phone_number = 888888;
display(&s;);
return 0;
}tput
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.

PP by Inst Dejene B FPII Page 9


Try to change the value of the variables inside the function in both the cases and see the
changes in the real variables.
Nested structures
We can have a structure as a member of a structure. When a structure includes another
structure, it is said to be a nested structure.
We can nest structures with In othr structures as in the following example.
#include <iostream.h>
#include <conio.h>
const int STR = 30 ;
struct address
{
char street [STR];
char post ;
float distance ; //in kilometers
};
struct employee
{
address branch;
address home ;
}
void main( ) {
employee emp1;
// employee branch adderase
cout << “enter branch street of the employee:”;
cin.get (emp1. branch.street, STR);
cout<<”enter branch post address”;
cin>>emp1.branch. Post;
cout<<”enter distance of the branch”;
cin>>emp1.branch.distance;

// employee home adderase


cout << “enter home street of the employee:”;
cin.get (emp1. home.street, STR);
cout<<”enter home post address”;
cin>>emp1.home. Post;
cout<<”enter distance of the home”;
cin>>emp1.home.distance;

cout<<” Employee’s branch street is :”<<emp1.


branch. street <<’and it is “<<emp1.
Branch. distance << “kms. Away “;
return 0;
}

PP by Inst Dejene B FPII Page 10

You might also like