befetrin.files.wordpress.com · web viewtype *name;type is the base type of the pointer and may be...

24

Click here to load reader

Upload: ngotruc

Post on 26-May-2018

214 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: befetrin.files.wordpress.com · Web viewtype *name;type is the base type of the pointer and may be any valid type. name is the name of pointer variable.The base type of the pointer

Kotebe University CollegeDepartment of Computer Science and Technology

Fundamental of programming II (CoSc 1014)Chapter Two

Be sure you understand function (chapter one) perfectly. Revise it seriously.Be sure you understand arrays perfectly. Revise array seriously.Structure gives you a hint in object oriented programming. Read it seriously.

2. Structure2.1. Introduction

Objects generally are too complex to be described by a single variable. An array can store multiple values, but all the values in that array must be of the same data type.

The restriction that all values must be of the same data type usually is not workable for objects. For example, each of us as human beings shares common characteristics such as a name and height. The value of each may be stored in a variable. However, these variables have different data types. Height may be stored in an integer or other numeric variable, but a name would be stored in a C-string or a C++ string class variable.

The name and height variables are related in the sense that they both describe different characteristics of the same person. However, if you declare them as follows, they do not belong together, but instead simply are two separate, independent variables:

  Char[20]name;   int height;   

C++ enables you to package related variables together into a structure. A structure may contain multiple variables of different data types, permitting the program to more faithfully imitate the complexity of a real-world object.

A structure, in reality, is a data type. However, it is not a data type built into C++, such as an int or a C-string. Instead, it is a programmer-defined data type.

2.2. Declaring a Structure (or Defining a Structure)

Since a structure is a programmer-defined data type, you must declare it so the compiler will understand what it is. The following code fragment declares a structure representing a person with two characteristics, name and height:

struct Person {   char[20]name;   int height;

1

Page 2: befetrin.files.wordpress.com · Web viewtype *name;type is the base type of the pointer and may be any valid type. name is the name of pointer variable.The base type of the pointer

};

The declaration starts with struct, which is a keyword indicating that a structure is being declared. “Person” is the name given for this structure. Other name could have given too. As with naming variables, you should give the structure a name which indicates what it represents.

The open and close curly braces define the body of the structure. Structures, like functions, have a body, enclosed in open and close curly braces. However, unlike functions, the close curly brace must be followed by a semicolon.

Note : Forgetting the semicolon after the close curly brace is a common mistake. You may not experience a compiler error, but instead a run-time error, particularly on multiple file projects, with the error message providing little or no clue that the real reason for the error is that you forgot the semicolon.

The variables that are related to each other are declared in the body of the structure. Each such variable is referred to as a member variable. A structure may have many member variables. Indeed, as discussed in a later section in this chapter, “Nesting Structures,” a variable of one structure may be a member variable of another structure.

A structure may be declared anywhere in your code. However, by convention, a structure usually is declared just below the preprocessor directives and above main, as in the following code fragment:

#include <iostream>#include <string>using namespace std;struct Person {   char[20]name;   int height;};int main (){   // code   return 0;}

You may ask declaring a structure the same place a global variable would be declared and you have been learned not to use global variables unless absolutely necessary. Can you guess why?

The reason is when we declare a structure; we are not declaring a variable. Instead, we are declaring a data type. By declaring the data type globally, we will be able to use that data type throughout the program. The reasons for not making variables global don’t apply to declaring a data type. For example, you can’t assign a value to a Person structure any more than you can assign a value to an int. Instead, you need to declare variables of the structure. That issue is discussed next.

2

Page 3: befetrin.files.wordpress.com · Web viewtype *name;type is the base type of the pointer and may be any valid type. name is the name of pointer variable.The base type of the pointer

2.3. Declaring a Structure Variable

Consider the room where a teacher teaches students. Each student is an instance of a Person structure, with their own name and height. Students also have weight, but I won’t talk about that variable (i.e. read about Abstract Data Type (ADT)). At this time, just one particular person or student is needed to be considered. In this case, someone who is looking for a particular student doesn’t ask where a generic Person is. Instead, He asks where he could find a particular person, identifying her specifically.

A generic person is the Person structure that in the previous section where you are shown how to declare. However, each particular person is an instance of the Person structure, and each such instance needs to be declared as a Person structure variable.

You declare a structure variable essentially the same as you declare a variable of a built-in data type. The following code declares a Person variable:

  Person p1;

As with the declaration of a variable of a built-in data type, the declaration of a structure variable starts with the data type, then a variable name, and closes with a semicolon to indicate to the compiler the end of the statement.

You also can declare multiple Person variables, such as:

  Person p1, p2, p3;

Indeed, if you want to declare all students in you class, you might want to declare an array of Person variables:

  Person p[43];

You may declare a structure variable essentially anywhere in your program; the same scope and lifetime rules apply just the way they do for integer, float, and other types of variables. Structure variables mostly act the same way other primitive variables act except that they are of programmer defined data types.

2.4. Accessing Structure Member Variables

Declaring a structure variable does not assign values to its member variables. You can access a member variable by the name of a structure variable, a dot operator, which looks like a period, and the name of the member variable. The following code assigns the value “Abebe Kebede” to the name member variable of the Person variable p1:

  p1.name = "Abebe Kebede";

Similarly, you could output the value of the member variable using the same syntax:

3

Page 4: befetrin.files.wordpress.com · Web viewtype *name;type is the base type of the pointer and may be any valid type. name is the name of pointer variable.The base type of the pointer

  cout << "The name of p1 is " << p1.name;

Don’t make the beginner’s mistake of using the name of the structure, rather than the name of the structure variable, as in the following example:

  Person.name = "Emily Kent";   // won't work!

The following program declares a structure, assign values to its members and outputs its values.

#include <iostream.h>#include <conio.h>struct Person {   char name[20];   int height;};int main (){ clrscr();   Person p;   cout << "Enter person's name: ";   cin.getline(p.name,20); // why cin>> is not used.   cout << "Enter height in cm: ";   cin >> p.height;   cin.ignore(); //why this line is used?          cout << endl;

  cout << "Outputting person data\n";   cout << "======================\n";   cout<<"name= "<<p.name <<endl;   cout<<"height= "<< p.height <<endl;   getch(); return 0;}

Some sample inputs and outputs are:

Enter person's name: Abebe AyalewEnter height in cm: 178

Outputting person data======================

name= Abebe Ayalew height= 178

4

Page 5: befetrin.files.wordpress.com · Web viewtype *name;type is the base type of the pointer and may be any valid type. name is the name of pointer variable.The base type of the pointer

2.5. Initializing a Structure

Structures can be initialized using initialization list. The following code fragment demonstrates how you can initialize a structure with an initialization list:

   Person p1 = {"Alemu Abebe", 160};

This may be a bit wondering, since an array is similarly initialized with an initialization list. However, there is an important difference. While all of the elements of an array share the same data type, the member variables of a structure may have different data types. This makes the order of the values in the initialization list particularly important. For example, the following code will result in a compiler error because the first member variable of the structure is a C-string and you cannot assign an integer to a C-string:

  Person p1 = {72, "Jeff Kent"};  // won't work

2.6. Array of Structures

An array of structure is just like an ordinary array except its elements are structure variables but not variables of primitive data types. In addition, each structure variables in the array are accessed through the array. For example the following code declares an array named Title with three elements which are structure variables of type Pencil.

Struct Pencil { char Name[25]; int length;};

Pencil Title [3];

The following figure shows the array “Title” pictorially.

Title[2].name=”abebe”; assigns “abebe” to second pencil structure variable in Title array

5

Page 6: befetrin.files.wordpress.com · Web viewtype *name;type is the base type of the pointer and may be any valid type. name is the name of pointer variable.The base type of the pointer

The following program declares a three-element Person array, assigns values to the member variables of each element, and then outputs their values:

#include <iostream.h>#include <conio.h>const int MAX = 3;struct Person {   char name[20];   int height;};int main (){ clrscr();   Person p[MAX];   for (int i = 0; i < MAX; i++)   {      cout << "Enter person's name: ";      cin.getline(p[i].name,20); // why cin>> is not used.      cout << "Enter height in cm: ";      cin >> p[i].height;      cin.ignore(); //why this line is used?         } cout << endl;   cout << "Outputting person data\n";   cout << "======================\n";   for (i = 0; i < MAX; i++) {       cout << "Person " << i + 1 << " Data: "<<endl;       cout<<" name= "<<p[i].name <<endl;       cout<<" height= "<< p[i].height <<endl;   }getch();return 0;}

Some sample input and output could be

Enter person's name: Abebe AyalewEnter height in cm: 178Enter person's name: Yohannes GetachewEnter height in cm: 172Enter person's name: Alemu KebedeEnter height in cm: 160

Outputting person data======================Person 1 Data: name= Abebe Ayalew height= 178Person 2 Data: name= Yohannes Getachew height= 172Person 3 Data: name= Alemu Kebede height= 160

6

Page 7: befetrin.files.wordpress.com · Web viewtype *name;type is the base type of the pointer and may be any valid type. name is the name of pointer variable.The base type of the pointer

You are highly recommended to hand trace the above program and produce the same output.

Exercise: consider a structure called book with member title, author, subject, book_id. Write a full program that inputs data for three books in a library and display the input data on the screen. Use array of structure.

2.7. Detail points in Structure

Structures are aggregate data types that is, they can be built using elements of several types including other structs. Consider the following structure definition:

struct Card{ char [20] face; char [20] suit;}; // end struct Card

Keyword struct introduces the definition for structure Card. The identifier Card is the structure name and is used in C++ to declare variables of the structure. In this example, the structure type is Card. Data declared within the braces of the structure definition are the structure's members. Members of the same structure must have unique names, but two different structures may contain members of the same name without conflict. Each structure definition must end with a semicolon.Forgetting the semicolon that terminates a structure definition is a syntax error.

The definition of Card contains two members of type char [20] face and suit. Structure members can be variables of the fundamental data types (e.g., int, double, etc.) or aggregates, such as arrays and other structures. Data members in a single structure definition can be of many data types. For example, an Employee structure might contain character-string members for the first and last names, an int member for the employee's age, a char member containing 'M' or 'F' for the employee's gender, a double member for the employee's hourly salary and so on.

Exercise: define Employee structure with members mentioned above.

A structure cannot contain an instance of itself. For example, a structure variable Card cannot be declared in the definition for structure Card.

The Card structure definition does not reserve any space in memory; rather, it creates a new data type that is used to declare structure variables. Structure variables are declared like variables of other types. The following declarations

Card oneCard;Card deck[ 52 ];Card *cardPtr;

declare oneCard to be a structure variable of type Card, deck to be an array with 52 elements of type Card and cardPtr to be a pointer to a Card structure. Variables of a given structure type can

7

Page 8: befetrin.files.wordpress.com · Web viewtype *name;type is the base type of the pointer and may be any valid type. name is the name of pointer variable.The base type of the pointer

also be declared by placing a comma-separated list of the variable names between the closing brace of the structure definition and the semicolon that ends the structure definition. For example, the preceding declarations could have been incorporated into the Card structure definition as follows:

struct Card{ char *face; char *suit;} oneCard, deck[ 52 ], *cardPtr;

In this case, the structure name is optional. If a structure definition does not contain a structure name, variables of the structure type may be declared only between the closing right brace of the structure definition and the semicolon that terminates the structure definition.

As a good programming practice, provide a structure name when creating a structure type. The structure name is required for declaring new variables of the structure type later in the

The only valid built-in operations that may be performed on structure objects are assigning a structure object to a structure object of the same type, taking the address (&) of a structure object, accessing the members of a structure object (in the same manner as members of a class are accessed) and using the sizeof operator to determine the size of a structure.

Structures can be initialized using initializer lists, as is done with arrays. For example, the declaration

Card oneCard = { "Three", "Hearts" };

creates Card variable oneCard and initializes member face to " Three" and member suit to "Hearts".

2.8. Nested Structures

In your previous programming courses, you have nested if statements within if statements, and loops within loops. You also may nest a structure within another structure. However, the needs for nested structures rarely happen.

Using our Person structure example, every person has a birthday. A birthday is a date. A date, in turn, may be defined by a structure that contains three member variables, all integers, which represent the month, day, and year of the particular date. The Date structure could be declared as follows:

struct Date{   int month;   int day;   int year;

8

Page 9: befetrin.files.wordpress.com · Web viewtype *name;type is the base type of the pointer and may be any valid type. name is the name of pointer variable.The base type of the pointer

};

The Person structure declaration then would be modified to add a member variable, of the structure Date, named bDay, to represent the person’s birthday:

struct Person {   string name;   int height;   Date bDay;};The following code modifies the previous one by adding the Date structure and the bDay Date member variable to the Person structure, as well as modifying the setValues function to also assign a value to the bDay Date member variable and the getValues function to output the value of that member variable:#include <iostream>#include <string>

struct Date{   int month;   int day;   int year;};struct Person {   string name;   int height;   Date bDay;};

int main (){   Person pers;   cout << "Enter person's name: ";   getline(cin, pers.name);   cout << "Enter height in inches: ";   cin >> pers.height;   cin.ignore();   cout << "Enter month, day and year of birthday separated by spaces: "   cin >> pers.bDay.month >> pers.bDay.day >> pers.bDay.year;   cin.ignore();

  cout << "Outputting person data\n";   cout << "======================\n";

cout << "Person's name: " << pers.name << endl;   cout << "Person's height in inches is: " << pers.height << endl;   cout << "Person's birthday in mm/dd/yyyy format is: "      << pers.bDay.month << "/" << pers.bDay.day      << "/" << pers.bDay.year << endl;   return 0;}

The following is some sample input and output:

Enter person's name: Abebe KebedeEnter height in inches: 78Enter month, day and year of birthday separated by spaces: 3 4 1211Outputting person data======================

9

Page 10: befetrin.files.wordpress.com · Web viewtype *name;type is the base type of the pointer and may be any valid type. name is the name of pointer variable.The base type of the pointer

Person's name: Abebe KebedePerson's height in inches is: 78Person's birthday in mm/dd/yyyy format is: 3/4/1211The Date structure must be declared before the Person structure. Otherwise, the compiler would not know what Date was in the declaration of the bDay member variable of the Person structure.

The above code sets the value of the person’s birthday. It cannot do so by:

  cin >> pers.bDay

The reason is that bDay is not an integer that can be assigned user input of an integer. Instead, it itself is also a structure. Therefore, it is necessary to drill down further into the member variables of bDay, month, day, and year, as in the following statement:

  cin >> pers.bDay.month >> pers.bDay.day >> pers.bDay.year;

Similarly, the the following statement cannot output the person’s birthday:

  cout << pers.bDay;

Instead, it must also drill down further into the member variables of bDay, month, day, and year, as in the following statement:

  cout << "Person's birthday in mm/dd/yyyy format is: "      << pers.bDay.month << "/" << pers.bDay.day      << "/" << pers.bDay.year << endl;

2.9. Structure, Reference and Pointer.2.9.1. Pointer and const

A pointer is a variable that holds a memory address. This address is the location of another object (typically, a variable) in memory. That is, if one variable contains the address of another variable, the first variable is said to point to the second.

A pointer declaration consists of a base type, an *, and the variable name. The general form of declaring a pointer variable is:

type *name;type is the base type of the pointer and may be any valid type. name is the name of pointer variable.The base type of the pointer defines what type of variables the pointer can point to.

10

Page 11: befetrin.files.wordpress.com · Web viewtype *name;type is the base type of the pointer and may be any valid type. name is the name of pointer variable.The base type of the pointer

Two special pointer operators are: * and &.The & is unary operator that returns the memory address of its operand. It is “the address of” operand.The * is complement of &. It is also a unary operator and returns the value located at the address that follows.

int i, *p;i = 5;p = &i;         //places the memory address of i into p

The expression *p will return the value of variable pointed to by p.

Just like normal variables, pointers can be declared constant. There are two different ways that pointers and const can be intermixed, and they are very easy to mix up.

To declare a const pointer, use the const keyword between the asterisk and the pointer name:

int nValue = 5;int *const pnPtr = &nValue;

Just like a normal const variable, a const pointer must be initialized to a value upon declaration, and its value cannot be changed. This means a const pointer will always point to the same value. In the above case, pnPtr will always point to the address of nValue. However, because the value being pointed to is still non-const, it is possible to change the value being pointed to via dereferencing the pointer:

*pnPtr = 6; // allowed, since pnPtr points to a non-const int

It is also possible to declare a pointer to a constant variable by using the const before the data type.

int nValue = 5;const int *pnPtr = &nValue;

Note that the pointer to a constant variable does not actually have to point to a constant variable! Instead, think of it this way: a pointer to a constant variable treats the variable as constant when it is accessed through the pointer.

Thus, the following is okay:

nValue = 6; // nValue is non-const

But the following is not:

11

Page 12: befetrin.files.wordpress.com · Web viewtype *name;type is the base type of the pointer and may be any valid type. name is the name of pointer variable.The base type of the pointer

*pnPtr = 6; // pnPtr treats its value as const

Because a pointer to a const value is a non-const pointer, the pointer can be redirected to point at other values:

int nValue = 5;int nValue2 = 6; const int *pnPtr = &nValue;pnPtr = &nValue2; // okay

Confused? To summarize:

A non-const pointer can be redirected to point to other addresses. A const pointer always points to the same address, and this address cannot be

changed.

A pointer to a non-const value can change the value it is pointing to. A pointer to a const value treats the value as const (even if it is not), and thus cannot

change the value it is pointing to.

Finally, it is possible to declare a const pointer to a const value:

const int nValue;const int *const pnPtr = &nValue;

A const pointer to a const value cannot be redirected to point to another address, nor can the value it is pointing to be changed.

Const pointers are primarily used for passing variables to functions.

2.9.2. References

References are a type of C++ variable that act as an alias to another variable. A reference variable acts just like the original variable it is referencing. References are declared by using an ampersand (&) between the reference type and the variable name:

int nValue = 5; // normal integerint &rnRef = nValue; // reference to nValue

The ampersand in this context does not mean “address of”, it means “reference to”. Let’s take a look at references in use:

nValue = 6; // nValue is now 6rnRef = 7; // nValue is now 7 cout << nValue; // prints 7nValue++;cout << rnRef; // prints 8

Using the address-of operator on a reference returns the address of the value being referenced:

12

Page 13: befetrin.files.wordpress.com · Web viewtype *name;type is the base type of the pointer and may be any valid type. name is the name of pointer variable.The base type of the pointer

cout << &nValue; // prints 0012FF7Ccout << &rnRef; // prints 0012FF7C

References are implicitly const. Like normal constant objects, references must be given a value upon declaration:

int nValue = 5;int &rnRef = nValue; // valid reference int &rnInvalidRef; // invalid, needs to reference something

Furthermore, the reference can not be “redirected” to another variable. Consider the following snippet:

int nValue = 5;int nValue2 = 6; int &rnRef = nValue;rnRef = nValue2; // assigns value 6 to nValue -- does NOT change the reference!

Const references

It is possible to declare a const reference. A const reference will not let you change the value it references:

int nValue = 5;const int &rnRef = nValue; 

rnRef = 6; // illegal -- rnRef is const

You can assign const references to literal values, though there is typically not much need to do so:

const int &rnRef = 6;Typical use of references

References are typically used for one of two purposes.

First, const references are often used as function parameters, which we talked about it in chapter one. Because const references allow us to access but not change the value of an object, they can be used to give a function access to an object, but give assurance to the caller that the function will not change the object. This helps prevent inadvertent side effects.

2.9.3. Using Reference and Pointer with Structure.

References and pointers have an interesting relationship — a reference acts like a const pointer that is implicitly dereferenced. Thus given the following:

int nValue = 5;int *const pnValue = &nValue;int &rnValue = nValue;

13

Page 14: befetrin.files.wordpress.com · Web viewtype *name;type is the base type of the pointer and may be any valid type. name is the name of pointer variable.The base type of the pointer

*pnValue and rnValue evaluate identically. As a result, the following two statements produce the same effect:

*pnValue = 6;rnValue = 6;

Similarly, a const reference acts just like a const pointer to a const object that is implicitly dereferenced.

Because references always “point” to valid objects, and can never be pointed to deallocated memory, references are safer to use than pointers. If a task can be solved with either a reference or a pointer, the reference should generally be preferred. Pointers should generally only be used in situations where references are not sufficient (such as dynamically allocating memory). That is why we used reference in our discussion of passing values by reference in chapter one.

Member selection

It is common to have either a pointer or a reference to a struct. As you learned previously, you can select the member of a struct using the member selection operator (.):

struct Something{    int nValue;    float fValue;}; // Member selection using actual struct variableSomething sSomething;sSomething.nValue = 5; // Member selection using reference to structSomething &rsSomething = sSomething;rsSomething.nValue = 5; // Member selection using pointer to structSomething *psSomething = &sSomething;(*psSomething).nValue = 5;

Note that the pointer dereference must be enclosed in parenthesis, because the member selection operator has a higher precedence than the dereference operator.

Because the syntax for access to structs and class members through a pointer is awkward, C++ offers a second member selection operator (->) for doing member selection from pointers. The following two lines are equivalent:

(*psSomething).nValue = 5; psSomething->nValue = 5;

14

Page 15: befetrin.files.wordpress.com · Web viewtype *name;type is the base type of the pointer and may be any valid type. name is the name of pointer variable.The base type of the pointer

This is not only easier to type, but is also much less prone to error because there are no precedence issues to worry about. Consequently, when doing member access through a pointer, always use the -> operator.

Suppose we have a pointer to structure as student *sptr; here sptr is a pointer to student. Now s1 is a variable of type student and sptr = &s1 and sptr is pointing to s1. How can we access the data with sptr? We cannot say *sptr.name. The precedence of dot operator (.) is higher than * operator. So dot operator is evaluated first and then * operator. The compiler will give error on the above statement. To get the results, we have to evaluate * operator first i.e. (*sptr).name will give the desired result. There is another easy and short way to access the structure’s data member i.e. using the arrow (->) in place of dot operator. We normally use the arrow (-> i.e. minus sign and then the greater than sign) to manipulate the structure’s data with pointers. So to access the name with sptr we will write:

sptr->name;

Remember the difference between the access mechanism of structure while using the simple variable and pointer. While accessing through a simple variable, use dotoperator i.e. s1.name While accessing through the pointer to structure, use arrowoperator i.e. sptr- >name;

Following is the example, depicting the access mechanism of structure’s data member using the pointer (using * and using ->) and reference (using .) to structure.

/* This program shows the access of structure data members with pointer to structure

*/

#include <iostream.h>

main()

{

// Declaration of student structure

struct student{

char name[64];

char course[64];

int age;

int year;

};

// Initializing the s1

student s1 = {"Ali", "C++ Programming", 22, 2002};

student *sptr;

// Assigning a structure to pointer

sptr = &s1;

// Assigning structure to a reference.

Student &sRef=s1;

cout << "Displaying the structure data members using pointers" << endl;

15

Page 16: befetrin.files.wordpress.com · Web viewtype *name;type is the base type of the pointer and may be any valid type. name is the name of pointer variable.The base type of the pointer

cout << "Using the * operator" << endl;

cout << endl;

cout << "The name is " << (*sptr).name << endl;

cout << "The course is " << (*sptr).course << endl;

cout << "The age is " << (*sptr).age << endl;

cout << "The year is " << (*sptr).year << endl;

cout << endl;

cout << "Using the -> operator" << endl;

cout << endl;

cout << "The name is " << sptr->name << endl;

cout << "The course is " << sptr->course << endl;

cout << "The age is " << sptr->age << endl;

cout << "The year is " << sptr->year << endl;

cout << "Using the reference variable" << endl;

cout << endl;

cout << "The name is " << sRef.name << endl;

cout << "The course is " << sRef.course << endl;

cout << "The age is " << sRef.age << endl;

cout << "The year is " << sRef.year << endl;

}The output of the program is:Displaying the structure data members using pointersUsing the * operatorThe name is AliThe course is C++ ProgrammingThe age is 22The year is 2002Using the -> operatorThe name is AliThe course is C++ ProgrammingThe age is 22The year is 2002Using the reference variableThe name is AliThe course is C++ ProgrammingThe age is 22The year is 2002

2.10. Passing Structure to Functions2.10.1. Passing simple structure to a function

There are two ways to pass the information in structures to functions. You can either pass the entire structure or pass the individual members of a structure. By default, structures are

16

Page 17: befetrin.files.wordpress.com · Web viewtype *name;type is the base type of the pointer and may be any valid type. name is the name of pointer variable.The base type of the pointer

passed by value. Structures and their members can also be passed by reference by passing either references or pointers.

To pass a structure by reference, pass the address of the structure object or a reference to the structure object. Arrays of structures like all other arrays are passed by reference. The syntax for passing structures or array of structures is similar with passing built in (or primitive) data types discussed in chapter one. The only difference is now variables of user defined data types (but not variables of built in data types) are sent to functions as argument.

The usual practice is to modularize the access of structures i.e., prepare two functions, the first function for populating the structure (or array of structure) and the second function for displaying the structure (or array of structure).

The following program passes a Person structure instance as an argument to two functions. The populate function assigns values to the member variables of the structure instance, whereas the display function outputs the values of the member variables of the structure instance:

#include <iostream>#include <string>struct Person {   char[30]name;   int height;};void populate(Person&);void display(const Person&);

int main (){   Person p1;   populate(p1);     cout << "Outputting person data\n";   cout << "======================\n";   display(p1);   return 0;}

void populate(Person& pers){   cout << "Enter person's name: ";   cin.getline(pers.name,30);   cout << "Enter height in cm: ";   cin >> pers.height;   cin.ignore();}

void display(const Person& pers){   cout << "Person's name is " << pers.name         << " and height is " << pers.height << endl;  }

The following is some sample input and output:

17

Page 18: befetrin.files.wordpress.com · Web viewtype *name;type is the base type of the pointer and may be any valid type. name is the name of pointer variable.The base type of the pointer

Enter person's name: Abebe AyalewEnter height in cm: 170Outputting person data======================Person's name: Abebe AyalewPerson's height in cm is: 170

Unlike an array name, a structure’s value is not an address. Therefore, to change the values of its member variables when passing a structure as a function argument, the structure needs to be passed by reference or by address. Therefore, in the populate function, which changes the member variables of the structure passed to it, the structure is passed by reference.

However, the structure also is passed by reference to the display function even though that function does not change the value of its member variables. The reason is that less memory is required to pass the address of an object than the object itself, which may take up a lot of bytes. However, here the structure instance in the display function’s argument list is preceded with the const keyword to prevent the function from inadvertently changing the values inside the structure instance.

Q. suppose, in the above program, p1 is passed by value. Name is a member of Person structure and is an array of characters. If your friend argues you that if name is an array, it should be passed by reference and the other friend argue that it should be passed by value because the structure is passed by value. Which position you support?Q. your friend wants to pass arrays by value, can you propose any way to do so?

2.1.1. Passing array of structure to a functionAs mentioned earlier, passing array of structure is similar with passing array of built in data types except that the array variable is now of programmer defined data type. As usual, arrays (including array of structures) are passed by reference but not by value. Note that the default way of passing simple structures is by value. However, simple structures are usually passed by reference for performance reason and when we want to reflect the change we made in the called function to the calling function. Passing structures (and especially large structures) by reference is more efficient than passing them by value (which requires the entire structure to be copied).

The following program demonstrates how to pass array of structure to a function

#include <iostream.h>#include <string.h>const int MAX = 3;struct Person {   char name[30];   int height;};void populate(Person pers[], int length);void display(const Person pers[], int length);

int main (){   Person p[MAX]; populate(p,MAX);

18

Page 19: befetrin.files.wordpress.com · Web viewtype *name;type is the base type of the pointer and may be any valid type. name is the name of pointer variable.The base type of the pointer

cout <<endl;     cout << "Outputting person data\n";   cout << "======================\n"; cout <<endl; display(p,MAX);   return 0;}void populate(Person pers[], int length){ for (int i = 0; i < length; i++)   {      cout << "Enter person's name: ";      cin.getline(pers[i].name,30);      cout << "Enter height in cm: ";      cin >> pers[i].height;      cin.ignore();         }}void display(const Person pers[], int length){ for (i = 0; i < length; i++) {       cout << "Person " << i + 1 << " Data: "<<endl;       cout << " name = "<<pers[i].name<<endl;       cout << " height = "<<pers[i].height << endl; }}

Some sample input and output could be

Enter person's name: Abebe KebedeEnter height in inches: 160Enter person's name: Ayalew BelayEnter height in inches: 170Enter person's name: Samson TeshomeEnter height in inches: 165

Outputting person data======================

Person 1 Data: name = Abebe Kebede height = 160Person 2 Data: name = Ayalew Belay height = 170Person 3 Data: name = Samson Teshome height = 165

19