0% found this document useful (0 votes)
29 views31 pages

Structure

Uploaded by

Bacha Tariku
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views31 pages

Structure

Uploaded by

Bacha Tariku
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

DILLA UNIVERSITY

COLLEGE OF ENGINEERING AND TECHNOLOGY


SCHOOL OF COMPUTING AND INFORMATICS
DEPARTMENT OF COMPUTER SCIENCE
Fundamental of Programming –II in C++
Chapter -4 Structure in C++

Prepared by Nega Teferra (M.Tech on CSE)


1
What is Structure?
 The term structure in C++ means both a user-defined type
which is a grouping of variables as well as meaning a
variable based on a user-defined structure type.
 Structure is a compound data type that contains different
variables of different types.
 For example, you want to store Student details like
student name, student roll num, student age.
 You have two ways to do it, one way is to create different
variables for each data, but the downfall of this approach
is that if you want to store the details of multiple
students, in that case it is not feasible to create separate
set of variables for each student.
Prepared by Nega Teferra (M.Tech on CSE) 2
Cont.…
 Once the type has been defined through the C++ “struct”
keyword, you can create variables from it just like you would
any other type
 A STRUCT is a C++ data structure that can be used to store
together elements of different data types.
 In C++, a structure is a user-defined data type.
 The structure creates a data type for grouping items of
different data types under a single data type.
 Use a struct when you need to store elements of different data
types under one data type.
 C++ structs are a value type rather than being a reference type.
 Use a struct if you don't intend to modify your data after
creation.
Prepared by Nega Teferra (M.Tech on CSE) 3
Struct Initialization
 To create a C++ structure, we use the struct keyword, followed
by an identifier.
 The identifier becomes the name of the struct. Here is the
syntax for creation of a C++ struct:
Syntax:
struct struct_name
{
// struct members
} ;
 In the above syntax, we have used the struct keyword.
 The struct_name is the name of the structure.
 The struct members are added within curly braces.
 These members probably belong to different data types.
 Do not forget this trailing semi-colon when defining a structure!
Prepared by Nega Teferra (M.Tech on CSE) 4
For example:
struct Person
{
char name[30];
char citizenship[20];
int age;
};
 In the above example, Person is a structure with three
members.
 The members include name, citizenship, and age.
 two members are char data types, while the remaining 1 is
integer when a structure is created, memory is not allocated.
 Memory is only allocated after a variable is added to the struct.5
Prepared by Nega Teferra (M.Tech on CSE)
Declaration of Structure Variable (instances)
 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 name, citizenship and age of three person.
 For this, we will define a structure named person (as declared above) and then
declare three variables, say p1, p2 and p3 (which will represent the three person
respectively) of type ‘person'.
struct person struct person
{ {
string name; string name;
string citizinship; string citizinship;
int age; int age;
}; }p1,p2,p3;
int main() int main()
{ {
person p1, p2, p3; //other statements;
//other statements; }
} Prepared by Nega Teferra (M.Tech on CSE) 6
Accessing Struct Members
 To access the struct members, we use the instance of the
struct and the dot (.) operator.
 Now, let's see how to enter the details of each person
i.e. name, citizen and age.
 Suppose we want to assign a name to the first person.
 For that, we need to access the name of the first person.
 We do this by writing
p1.name = "Mohhamed";
 This means that we use dot (.) to use variables in a
structure.
 p1.name can be understood as name of p1.
Prepared by Nega Teferra (M.Tech on CSE) 7
Cont.…
Note:
 You cannot initialize member variables in a structure definition.
 The following is wrong and will not compile:
struct date
{
int day = 24, month = 10, year = 2001;
};
 A structure definition has the same type of scoping as a variable.
 If you define a structure in a function, you will only be able to use it
there.
 If you define it in a nested statement block, you will only be able to
use it inside there and any statement blocks nested within it.
 But the most common place is defining it globally, as in outside of any
functions or blocks.
 Typically, you’ll want to be able to create variables of the defined
structure anywhere in your program, so the definition will go at the
top. Prepared by Nega Teferra (M.Tech on CSE) 8
Structure Demonstration-1
4. Create a struct named Person.
5. The beginning of the struct body.
6. Create a struct member named roll_no of type
integer.
7. Create a struct member named name of type string.
8. Create a struct member named name of type string.
9. End of the struct body.
10. Call the main() function. The program logic should
be added within the body of this function.
11. The beginning of the main function.
12. Create an instance of the struct student and giving
it the name stud.
13. Set the value of struct member roll_no to 1.
14. Set the value of struct member name to "Nega".
15. Set the value of struct member ID to "RCS-111/11".
16. Print the value of the struct member Roll_no,name
Code Explanation: and ID on the console.
look at the line number before each statements 17. The program should return a value if it runs
successfully.
Prepared by Nega Teferra (M.Tech on CSE) 18. End of the main() function. 9
Structure Demonstration -2

Prepared by Nega Teferra (M.Tech on CSE) 10


Array of Structures
 An array is a collection of data items of the same type.
 Each element of the array can be int, char, float, double, or
even a structure.
 We have seen that a structure allows elements of different
data types to be grouped together under a single name.
 This structure can then be thought of as a new data type in
itself.
 So, an array can comprise elements of this new data type.
 An array of structures finds its applications in grouping the
records together and provides for fast accessing.
struct student
{
int roll;
string name;
string ID;
}; Prepared by Nega Teferra (M.Tech on CSE) 11
Cont.…
 Since an array can contain similar elements, the combination
having structures within an array is an array of structures.
 To declare an array of structures, you must first define a
structure and then declare an array variable of that type.
 For example, to store information of 100 members of the
student, you need to create an array.
 Now, to declare a 100-element array of structures of type
sttudent, we will write :
student stud[100];
 This creates 100 sets of variables that are organized as
defined in the structure student.
 To access a specific structure, index the structure name.
 For instance, to print the ID of structure 8, write :
cout << stud[7].ID ; Prepared by Nega Teferra (M.Tech on CSE) 12
Demonstrating Array of structure

13
Prepared by Nega Teferra (M.Tech on CSE)
Array within Structures
 A structure is a data type in C++ that allows a group of
related variables to be treated as a single unit instead of
separate entities.
 A structure may contain elements of different data types
– int, char, float, double, etc.
 It may also contain an array as its member.
 Such an array is called an array within a structure.
 An array within a structure is a member of the structure
and can be accessed just as we access other elements of
the structure.

Prepared by Nega Teferra (M.Tech on CSE) 14


Cont.…
 As already mentioned, a structure element may be either simple or complex.
 A complex structure may itself be a structure or an array.
 When a structure element happens to be an array, it is treated in the same way as
arrays are treated.
 The only traditional thing to be kept in mind is that, to access it, its structure name
followed by a dot (.) and the array name is to be given. For example, consider this
structure :
struct student
{
int rollno ;
char name[21] ;
float marks[5] ;
}learner ;
 The above declared structure variable learner is of structure type student that
contains an element which is an array of 5 floats to store marks of a student in 5
different subjects.
 To reference marks of 3rd subject of structure learner, we will write :
learner.marks[2] ;
Prepared by Nega Teferra (M.Tech on CSE) 15
Demonstrating Array within structure

Prepared by Nega Teferra (M.Tech on CSE) 16


Pointers to Structure
• C++ allows pointers to structures just as it allows pointers to int or
char or float or any other data type.
• The pointers to structures are known as structure pointers.
• It's possible to create a pointer that points to a structure.
• It is similar to how pointers pointing to native data types like int, float,
double, etc. are created.
• Note that a pointer in C++ will store a memory location.

Prepared by Nega Teferra (M.Tech on CSE) 17


Declaration and Use of Structure Pointers
 Just like other pointers, the structure pointers are declared by placing asterisk
(∗) in front of a structure pointer's name.
 It takes the following general form :
struct-name ∗struct-pointer ;
 where struct-name is the name of an already defined structure and struct-pointer
is the pointer to this structure.
 For example, to declare dt-ptr as a pointer to already defined structure date, we
shall write
date ∗ dt-ptr ;
 The declaration of structure type and the structure pointer can be combined in
one statement. For example,

struct date struct date


{ {
int dd, mm, yy ;
is same as int dd, mm, yy ;
} ; } ∗ dt_ptr ;
date ∗ dt_ptr ;
Prepared by Nega Teferra (M.Tech on CSE) 18
Cont.…
 Using structure pointers, the members of structures are
accessed using arrow operator ->.
 To refer to the structure members using -> operator, it is
written as

struct-pointer -> structure-member


 That is, to access dd and yy with dt_ptr, we shall write

dt_ptr -> yy
and
dt_ptr -> dd

Prepared by Nega Teferra (M.Tech on CSE) 19


Demonstrating Pointers to structure

dt_ptr->dd is same as (*dt_ptr).dd


dt_ptr->mm is same as (*dt_ptr).mm
dt_ptr->yy is same as (*dt_ptr).yy
Prepared by Nega Teferra (M.Tech on CSE) 20
Structure and Function
 So far, all structures used in the preceding examples have
been global and hence were available to all the functions
within program.
 But, if you have a structure local to a function and you
need to pass its values to another function, then it can be
achieved in two ways :
 by passing individual structure elements
 by passing the entire structure
 Both these ways can be achieved by call by value as well as
call by reference method of passing variables

Prepared by Nega Teferra (M.Tech on CSE) 21


Passing Structure Elements to Functions
 When an element of a structure is passed to a function, you are
actually passing the values of that element to the function.
 Therefore, it is just like passing a simple variable (unless, of
course, that element is complex such as an array of character).
 For example, consider the following structure :
struct date
{
short day ,month , year ;
}Bdate ;
 Individual elements of this structure can be passed as follows :
func1(Bdate.day, Bdate.month, Bdate.year) ;

Prepared by Nega Teferra (M.Tech on CSE) 22


Cont.…
 The above function-call invokes a function, func1() by passing
values of individual structure elements of structure Bdate.
 The function can either receive the values by creating its own
copy for them (call by value) or by creating references for
the original variables (call by reference).
 If You want that the values of the structure elements should
not be altered by the function, then you should pass the
structure elements by value and if you want the function to
alter the original values, then you should pass the structure
elements by reference.
 But remember if one of the structure elements happens to be
an array, it will automatically be passed by reference as the
arrays cannot be passed by value.
Prepared by Nega Teferra (M.Tech on CSE) 23
Passing Entire Structure to Function
 Passing entire structures makes the most sense when the
structure is relatively compact.
 The entire structure can be passed to the functions both ways
by value and by reference.
 Passing by value is useful when the original values are not to be
changed and passing by reference is useful when original values
are to be changed.

Pass Structure to Function Call by Value


 When a structure is used as an argument to a function, the
entire structure is passed using the standard call-by-value
method.
 Of course, this means that any changes made to the contents
of the structure inside the function to which it is passed do not
affect the structure used as an argument. 24
Prepared by Nega Teferra (M.Tech on CSE)
passing structure to function by value

25
Prepared by Nega Teferra (M.Tech on CSE)
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.
 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 the structure variable' in its parameter.

Prepared by Nega Teferra (M.Tech on CSE) 26


passing structure to function by reference

Prepared by Nega Teferra (M.Tech on CSE) 27


How to return the Structure from a Function
 In this example we have two functions one gets the values
from user, assign them to structure members and returns
the structure and the other function takes that structure
as argument and print the details.
 Just like other types, functions can return structures also.
 Then the return type of the function is the same as that
of the type of the structure returned.
 Study the following sample code.

Prepared by Nega Teferra (M.Tech on CSE) 28


Returning Structures from Functions

Prepared by Nega Teferra (M.Tech on CSE) 29


Nested Structure
It is possible to define a structure inside a structure definition
and create variables from it at the same time. For example:
struct moment
{
struct date
{
int day, month, year;
} theDate;
struct time
{
int second, minute, hour;
} theTime;
}; Prepared by Nega Teferra (M.Tech on CSE) 30
Demonstration of Nested Structure

Prepared by Nega Teferra (M.Tech on CSE) 31

You might also like