You are on page 1of 67

Structured Data And

Pointers

Chung-Ming Chen
Department of Biomedical Engineering

Textbook:
1. C++ Programming: From Problem Analysis to Program Design, 8th Edition, D.S. Malik
2. Data Structures Using C++, 2nd Edition, D.S. Malik Page 1
Structured Data Type: Arrays

l An array is a collection of a fixed number of components


(also called elements) all of the same data type and in
contiguous (that is, adjacent) memory space.
l One dimensional array: the components are arranged in a
list form
– Declaration
datatype arrayName[intExp]
e.g., int num[5];
– Initialization
u During Declaration
– double sales[5] = {12.25, 32.50, 16.90, 23, 45.68];
– int list[10] = {0};//declare a list of 10 elements with all elements initialized to 0
– int list[10] = {8, 5, 12};//only the first 3 elements are initialized
– int list [] = {5, 6, 3};//declare a list of three elements with initialization
u Use loops to do element by element assignment
Spring 2024 Data Structure 2
Arrays as Parameters to Functions

l By reference only: In C++, arrays are passed by


reference only.
– Because arrays are passed by reference only, you do not use the
symbol & when declaring an array as a formal parameter.
l When declaring a one-dimensional array as a formal
parameter, the size of the array is usually omitted. If you
specify the size of a one-dimensional array when it is
declared as a formal parameter, the size is ignored by the
compiler.
void initialize(int list[], int listSize)
{
for (int count = 0; count < listSize; count++)
list[count] = 0;
}

Spring 2024 Data Structure 3


Notices on Array Processing
l Array Index Out of Bounds
– C++ does not check whether the index value is within range—that is,
between 0 and ARRAY_SIZE - 1. If the index goes out of bounds and the
program tries to access the component specified by the index, then
whatever memory location is indicated by the index that location is
accessed. This situation can result in altering or accessing the data of a
memory location that you never intended to modify or access, or in trying
to access protected memory that causes the program to instantly halt.
l A Restriction on Array Processing
– Consider the following statements:
int myList[5] = {0, 4, 8, 12, 16};
int yourList[5];
– Suppose that you want to copy the elements of myList into the
corresponding elements of yourList. The following statement is illegal:
yourList = myList; // Aggregate operations on an array is not allowed.

Spring 2024 Data Structure 4


Constant Arrays as Formal Parameters

l Recall that when a formal parameter is a reference


parameter, then whenever the formal parameter changes,
the actual parameter changes as well. However, even
though an array is always passed by reference, you can
still prevent the function from changing the actual
parameter by using the reserved word const in the
declaration of the formal parameter.
l The function example can modify the array x, but not the
array y.
void example(int x[], const int y[], int sizeX, int sizeY)
{
.
.
.
}

Spring 2024 Data Structure 5


Structured Data Type: Records (structs)

l struct: A collection of a fixed number of components in which the


components are assessed by name. The components may be of
different types.
l The components of a struct are called the members of the struct.
l Define a struct and declare struct variables, an example:

houseType tempHouse;

Spring 2024 Data Structure 6


struct Processing

l Access struct Members


Ø structVariableName.memberName
Ø e.g., tempHouse.numofBedrooms = 3;
l struct Assignment
struct studentType
{
string firstName;
string lastName;
char courseGrade
int testScore;
int programmingScore;
double GPA;
}
studentType newStudent;
studentType student;
l The value of newStudent can be copied into student by
student = newStudent;

Spring 2024 Data Structure 7


struct Processing

l struct Comparison (Relational Operators)


To compare struct variables, you compare them member-
wise. As with an array, no aggregate relational operations
are performed on a struct. For example, to compare the
values of student and newStudent, you must compare them
member-wise, as follows:
if (student.firstName == newStudent.firstName &&
student.lastName == newStudent.lastName)
.
.
.

Spring 2024 Data Structure 8


struct Processing

l struct Variables and Functions


– A struct variable can be passed as a parameter either by value or by
reference, and
– A function can return a value of type struct.

struct studentType {
//...
}

studentType newStudent, seniorStudent;

void PassByValue(studentType student); //prototype


void PassByReference(studentType& student); //prototype

PassByValue(newStudent);
PassByReference(seniorStudent);

Spring 2024 Data Structure 9


Arrays in structs

l A list is a set of elements of the same type. Thus, a list has two things
associated with it: the values (that is, elements) and the length.
const int ARRAY_SIZE = 1000;
struct listType
{
int listElem[ARRAY_SIZE]; //array containing the list
int listLength; //length of the list
} intList; int seqSearch(constlistType& list, int
searchItem)
l Consider the function on the right: The {
formal parameter list of the function int loc;
bool found = false;
seqSearch is declared as a constant for (loc = 0; loc < list.listLength; loc++)
reference parameter. What are the pros if (list.listElem[loc] == searchItem)
{
and cons of this declaration ? found = true;
– Data protection break;
}
– Memory allocation if (found)
– Duplication time return loc;
else
return -1;
}

Spring 2024 Data Structure 10


structs in Arrays

l For a list of entities with the same struct, e.g., employees’ salary info
struct employeeType
{
string firstName;
string lastName;
int personID;
string deptID;
double yearlySalary;
double monthlySalary;
double yearToDatePaid;
double monthlyBonus;
}
double payCheck; //variable to calculate the paycheck
for (int counter = 0; counter < 50; counter++)
employeeType employees[50]; {
cout << employees[counter].firstName << " "
<< employees[counter].lastName << " ";
payCheck = employees[counter].monthlySalary +
employees[counter].monthlyBonus;
employees[counter].yearToDatePaid =
employees[counter].yearToDatePaid + payCheck;
cout << setprecision(2) << payCheck << endl;
}

Spring 2024 Data Structure 11


structs within a struct
struct nameType struct contactType employeeType newEmployee;
{ {
string first; string phone;
string middle; string cellphone;
string last; string fax;
}; string pager;
struct addressType string email;
{ };
string address1;
string address2; struct employeeType
string city; {
string state; nameType name;
string zip; string empID;
}; addressType address;
struct dateType dateType hireDate;
{ dateType quitDate;
int month; contactType contact;
int day; string deptID;
int year; double salary;
}; };

newEmployee.contact.cellphone
Spring 2024 Data Structure 12
Classes and Objects Oriented Design

Spring 2024 Data Structure 13


Classes and Objects

l In object-oriented design (OOD), the first step is to identify


the components, called objects. An object combines data
and the operations on that data in a single unit, which is
called a class in C++.
l A class is a collection of a fixed number of components,
which are called the members of the class.
l The general syntax for defining a class is:
class classIdentifier
{
classMemberList
}
in which classMemberList consists of variable declarations
and/or functions.

Spring 2024 Data Structure 14


A Class

l If a member of a class is a variable, you declare it just like


any other variable.
l If a member of a class is a function, you typically use the
function prototype to declare that member.
l If a member of a class is a function, it can (directly)
access any member of the class—member variables and
member functions. That is, when you write the definition
of a member function, you can directly access any
member variable of the class without passing it as a
parameter. The only condition is that you must declare an
identifier before you can use it.

Spring 2024 Data Structure 15


Member Categories

l The members of a class are classified into three


categories: private, public, and protected.
– By default, all members of a class are private.
– If a member of a class is private, you cannot access it directly
from outside of the class.
– A public member is accessible outside of the class.
– To make a member of a class public, you use the member
access specifier public with a colon, :
– If a member of a base class needs to be accessed by a derived
class, that member is declared under memberAccessSpecifier
protected.

Spring 2024 Data Structure 16


An Example of Class Declaration
l In a call to the function equalTime, the class clockType
formal parameter receives the address of {
the actual parameter, but the formal public:
parameter cannot modify the value of the void setTime(int, int, int);
void getTime(int&, int&, int&) const;
actual parameter. (Why not using passed void printTime() const;
by value ?) void incrementSeconds();
void incrementMinutes();
l The word const at the end of the member void incrementHours();
functions, e.g., getTime, specifies that bool equalTime(const clockType&) const;
these functions cannot modify the private:
int hr;
member variables of a variable of type int min;
clockType. int sec;
l Member variables and functions can be };

private or public.
l Variable Declaration
clockType myClock;
clockType yourClock;
l Accessing Class Members
classObjectName.memberName
Spring 2024 Data Structure 17
Implementation of Member Functions
l Accessor function: A member function of a class that only accesses (that is, does not
modify) the value(s) of the member variable(s).
l Mutator function: A member function of a class that modifies the value(s) of the
member variable(s).
// Mutator Function // Mutator Function
void clockType::incrementHours() void clockType::setTime(int hours, int minutes, int
{ seconds)
hr++; {
if (hr > 23) if (0 <= hours && hours < 24) hr = hours;
hr = 0; else hr = 0;
} if (0 <= minutes && minutes < 60) min = minutes;
else min = 0;
if (0 <= seconds && seconds < 60) sec = seconds;
else sec = 0;
}
// Accessor Function
void clockType::getTime(int&
hours, int& minutes, int&
seconds) const // Accessor Function
{ bool clockType::equalTime(const clockType&
hours = hr; otherClock) const
minutes = min; {
seconds = sec; return (hr == otherClock.hr
} && min == otherClock.min
&& sec == otherClock.sec);
}

Spring 2024 Data Structure 18


Constructors
l To guarantee that the member variables of a class are initialized, you
use constructors. There are two types of constructors: with parameters
and without parameters. The constructor without parameters is called the
default constructor.
l Properties:
– The name of a constructor is the same as the name of the class.
– A constructor is a function and it has no type. That is, it is neither a value-returning
function nor a void function.
– A class can have more than one constructor. However, all constructors of a class
have the same name.
– If a class has more than one constructor, the constructors must have different formal
parameter lists. That is, either they have a different number of formal parameters or,
if the number of formal parameters is the same, then the data type of the formal
parameters, in the order you list, must differ in at least one position.
– Constructors execute automatically when a class object is declared and enters its
scope.
– Which constructor executes depends on the types of values passed to the class
object when the class object is declared.
Spring 2024 Data Structure 19
Constructors
clockType::clockType() //default constructor class clockType
{ {
hr = 0; public:
min = 0; void setTime(int, int, int);
sec = 0; void getTime(int&, int&, int&)
} const;
void printTime() const;
void incrementSeconds();
void incrementMinutes();
//Constructor with parameters void incrementHours();
clockType::clockType(int hours, int minutes, bool equalTime(const clockType&)
int seconds) const;
{ clockType(int, int, int);
setTime(hours, minutes, seconds); //constructor with parameters
} clockType(); //default constructor

private:
int hr;
l Invoking the Default Constructor int min;
int sec;
className classObjectName; };
clockType yourClock;
l Invoking a Constructor with Parameters
className classObjectName(argument1, argument2, …);
clockType myClock(5, 12, 40);
Spring 2024 Data Structure 20
Constructors and Default Parameters

l In the definition of the class clockType, you can replace both


constructors
clockType(int, int, int);
clockType();
using the following statement.
clockType(int = 0, int = 0, int=0); //Line 1
l If you replace the constructors of the class clockType with the
constructor in Line 1, then you can declare clockType objects with
zero, one, two, or three arguments, as follows:
clockType clock1; // initialized to hr = 0, min = 0, sec = 0
clockType clock2(5); // initialized to hr = 5, min = 0, sec = 0
clockType clock3(12, 30); // initialized to hr = 12, min = 30, sec = 0
clockType clock4(7, 34, 18); // initialized to hr = 7, min = 34, sec = 18

Spring 2024 Data Structure 21


In-Class Initialization
l If an object is declared with parameters, the class clockType
{
default values are overridden by the public:
constructor with the parameters, e.g., void setTime(int, int, int);
void getTime(int&, int&, int&)
clockType myTime; //hr=min=sec=0 const;
void printTime() const;
clockType yourTime(3, 40, 18); void incrementSeconds();
void incrementMinutes();
l clockType() {} void incrementHours();
bool equalTime(const clockType&)
This is a complete definition of the default const;
clockType() {}
constructor. The {} sepcifies the empty body clockType(int, int, int);
of the default constructor’s definition. This is //constructor with parameters

an example of in-line function definition of a private:


class member. Because the complete int hr = 0; //in-class initialization
int min = 0;
definition is included in the class definition, int sec = 0;
we do not need to provide its definition in the };

implementation file.

Spring 2024 Data Structure 22


Destructors

l Like constructors, destructors are also functions. Moreover, like


constructors, a destructor does not have a type. That is, it is neither a
value-returning function nor a void function. However, a class can
have only one destructor, and the destructor has no parameters. The
name of a destructor is the tilde character (~), followed by the name
of the class. For example, the name of the destructor for the class
clockType is:
~clockType();
l The destructor automatically executes when the class object goes
out of scope.

Spring 2024 Data Structure 23


Class personType

Spring 2024 Data Structure 24


Member Function of class personType

Spring 2024 Data Structure 25


Inheritance
l Suppose that you want to design the class partTimeEmployee to
implement and process the characteristics of a part-time employee.
l The main features : name, pay rate, and number of hours worked.
l Approaches:
– design the class partTimeEmployee from scratch, or
– extend the definition of the class personType by adding additional members
(data and/ or functions)
l Idea: create the class partTimeEmployee without making any physical
changes to the class personType by adding only the members that are
necessary.
l For example, because the class personType already has members to store
the first name and last name, we will not include any such members in the
class partTimeEmployee . In fact, these member variables will be inherited
from the class personType .

Spring 2024 Data Structure 26


Inheritance
l The new classes created from the existing classes are called derived
classes.
l The existing classes are called the base classes.
l The derived classes inherit the properties of the base classes.
l Each derived class, in turn, can become a base class for a future
derived class.
l Single inheritance: the derived class is derived from single base
class.
l Multiple inheritance: the derived class is derived from more than one
base class.
Base class

Spring 2024 Data Structure 27


General Syntax of A Derived Class

class className: memberAccessSpecifier baseClassName


{
member list
};

l memberAccessSpecifier : public, protected, or private (default)


l Suppose we have defined a class called shape :

class circle: public shape


{
.
.
.
};

Spring 2024 Data Structure 28


Notes on Base and Derived Classes

l The private members of a base class are private to the base class;
hence, the members of the derived class cannot directly access them.
In other words, when you write the definitions of the member functions
of the derived class, you cannot directly access the private members of
the base class.
l The public members of a base class can be inherited either as public
members or as private members by the derived class. That is, the
public members of the base class can become either public or private
members of the derived class.

l The derived class can include additional members—data and/or


functions.

Spring 2024 Data Structure 29


Notes on Base and Derived Classes

l The derived class can redefine the public member functions of the base
class. That is, in the derived class, you can have a member function
with the same name, number, and types of parameters as a function in
the base class. However, this redefinition applies only to the objects of
the derived class, not to the objects of the base class.
l All member variables of the base class are also member variables of
the derived class. Similarly, the member functions of the base class
(unless redefined) are also member functions of the derived class.
(Remember Rule 1 when accessing a member of the base class in the
derived class.)

Spring 2024 Data Structure 30


class rectangleType
class rectangleType
{
public:
void setDimension(double l, double w);
//Function to set the length and width of the rectangle.; Postcondition: length = l; width = w;
double getLength() const;
//Function to return the length of the rectangle.; Postcondition: The value of length is returned.
double getWidth() const;
//Function to return the width of the rectangle.; Postcondition: The value of width is returned.
double area() const;
//Function to return the area of the rectangle.
//Postcondition: The area of the rectangle is calculated and returned.
double perimeter() const;
//Function to return the perimeter of the rectangle.
//Postcondition: The perimeter of the rectangle is calculated and returned.
void print() const;
//Function to output the length and width of the rectangle.
rectangleType();
//Default constructor; Postcondition: length = 0; width = 0;
rectangleType(double l, double w);
//Constructor with parameters; Postcondition: length = l; width = w;
private:
double length;
double width;
};
Spring 2024 Data Structure 31
Member Functions of class rectangleType
void rectangleType::setDimension(double l, double w) double rectangleType::perimeter() const
{ {
if (l >= 0) return 2 * (length + width);
length = l; }
else void rectangleType::print() const
length = 0; {
if (w >= 0) cout << "Length = " << length
width = w; << "; Width = " << width;
else }
width = 0; rectangleType::rectangleType(double l, double w)
} {
double rectangleType::getLength() const setDimension(l, w);
{ }
return length; rectangleType::rectangleType()
} {
double rectangleType::getWidth() const length = 0;
{ width = 0;
return width; }
}
double rectangleType::area() const
{
return length * width;
}

Spring 2024 Data Structure 32


class boxType Inheriting rectangleType

class boxType: public rectangleType


{
public:
void setDimension(double l, double w, double h);
//Function to set the length, width, and height of the box.
//Postcondition: length = l; width = w; height = h;
double getHeight() const;
//Function to return the height of the box.
//Postcondition: The value of height is returned.
double area() const; Override the member function of the base class
//Function to return the surface area of the box.
//Postcondition: The surface area of the box is calculated and returned.
double volume() const;
//Function to return the volume of the box.
//Postcondition: The volume of the box is calculated and returned.
void print() const;
//Function to output the length, width, and height of a box.
boxType();
//Default constructor
//Postcondition: length = 0; width = 0; height = 0;
boxType(double l, double w, double h);
//Constructor with parameters
//Postcondition: length = l; width = w; height = h;
private:
double height;
};

Spring 2024 Data Structure 33


Notes on class boxType
l Supposed we want to write the definition of the member function print
of the class boxType.
l The member variables length and width are private members of the
class rectangleType, and so cannot be directly accessed in the class
boxType. Therefore, when writing the definition of the function print of
the class boxType, we cannot access length and width directly.
l The member variables length and width of the class rectangleType are
accessible in the class boxType through the public member functions
of the class rectangleType. Therefore, when writing the definition of the
member function print of the class boxType, we first call the member
function print of the class rectangleType to print the values of length
and width . After printing the values of length and width, we output
the values of height.
void boxType::print() const
{
rectangleType::print();
cout << "; Height = " << height;
}

Spring 2024 Data Structure 34


Member Functions of class boxType
void boxType::setDimension(double l, double w, double h)
{
rectangleType::setDimension(l, w);
if (h >= 0)
height = h;
else
height = 0;
}

double boxType::getHeight() const


{
return height;
}

double boxType::area() const


{
return 2 * (getLength() * getWidth()
+ getLength() * height
+ getWidth() * height);
}

double boxType::volume() const


{
return rectangleType::area() * height;
}

Spring 2024 Data Structure 35


Constructors of Derived and Base Classes

l The constructors of a derived class can (directly) initialize only the


(public data) members inherited from the base class of the derived
class.
l When a derived class object is declared, it must also trigger the
execution of one of the base class’s constructors.
l This triggering of the base class’s constructor is specified in the
heading of the definition of a derived class constructor.
boxType::boxType(double l, double w, double h)
: rectangleType(l, w) //trigger the execution of the base class constructor with parameters
{
if (h >= 0)
height = h;
else
height = 0;
}

//Examples:
rectangleType myRectangle(5.0, 3.0);
boxType myBox(6.0, 5.0, 4.0);

Spring 2024 Data Structure 36


class partTimeEmployee

Spring 2024 Data Structure 37


Member Functions of class partTimeEmployee

Spring 2024 Data Structure 38


Destructors in a Derived Class

l Destructors are typically used to deallocate dynamic


memory allocated to the objects of a class.
l When a derived class object goes out of scope, it
automatically invokes its destructor.
l When the destructor of the derived class executes, it
automatically invokes the destructor of the base class.
l When the destructor of the derived class executes, it
executes its own code first and then calls the destructor of
the base class.

Spring 2024 Data Structure 39


Protected Members of a Class

l The private members of a class are private to the class and


cannot be directly accessed outside the class.
l The derived class cannot access private members of a class.
l For a base class to give access to a member to its derived
class and still prevent its direct access outside the class, you
must declare that member under the member access
specifier protected.
l The accessibility of a protected member of a class is in
between public and private. A derived class can directly
access the protected member of a base class.

Spring 2024 Data Structure 40


Inheritance as public, protected, or private
class B: memberAccessSpecifier A
{
. either public, protected or private
.
.
};
1. If memberAccessSpecifier is public—that is, the inheritance is
public—then:
a. The public members of A are public members of B. They can be directly
accessed in class B.
b. The protected members of A are protected members of B. They can be directly
accessed by the member functions (and friend functions) of B.
c. The private members of A are hidden to B. They can be accessed by the
member functions (and friend functions) of B through the public or protected
members of A.

Spring 2024 Data Structure 41


Inheritance as public, protected, or private
2. If memberAccessSpecifier is proteced—that is, the inheritance is
protected—then:
a. The public members of A are protected members of B. They can be accessed
by the member functions (and friend functions) of B.
b. The protected members of A are protected members of B. They can be
accessed by the member functions (and friend functions) of B.
c. The private members of A are hidden to B. They can be accessed by the
member functions (and friend functions) of B through the public or protected
members of A.
3. If memberAccessSpecifier is private—that is, the inheritance is
private—then:
a. The public members of A are private members of B. They can be accessed by
the member functions (and friend functions) of B.
b. The protected members of A are private members of B. They can be accessed
by the member functions (and friend functions) of B.
c. The private members of A are hidden to B. They can be accessed by the
member functions (and friend functions) of B through the public or protected
members of A.
Spring 2024 Data Structure 42
Pointers and Array-based Lists

Spring 2024 Data Structure 43


Pointer Data Type and Pointer Variables

l Recall that a data type is a set of values, called the domain of the
data type, together with a set of operations.
l In addition to these two properties, until now, all of the data types you
have encountered have one more thing associated with them: the
name of the data type. For example, there is a data type called int.

l Pointer Data Type: The values belonging to pointer data types are
the memory addresses of your computer. However, there is no name
associated with the pointer data type in C++. Because the domain,
(that is, the values of a pointer data type), consists of addresses
(memory locations), a pointer variable is a variable whose content is
an address, that is, a memory location.

l Pointer Variables: A variable whose content is an address (that is, a


memory address) and is therefore said to point to a memory address.

Spring 2024 Data Structure 44


Declaring Pointer Variables
datatype *identifier;
int *p;
char *ch;
l In these statements, both p and ch are pointer variables. The content
of p (when properly assigned) points to a memory location of type int,
and the content of ch points to a memory location of type char.
Usually p is called a pointer variable of type int, and ch is called a
pointer variable of type char.
l The character * can appear anywhere between the data type name
and the variable name. For examples, the following three statements
are equivalent.
int *p
int* p
int * p;
l C++ provides two operators—the address of operator (&) and the
dereferencing operator (*)—to work with pointers.
Spring 2024 Data Structure 45
Dereferencing Operator (*)

l In C++, the asterisk character, *, commonly called the dereferencing


operator or indirection operator, is a unary operator that refers to
the object to which its operand (that is, the pointer) points. For
example, given the statements:
int x = 25;
int *p;
p = &x;
the statement
cout << *p << endl;
prints the value stored in the memory space to which p points, which
is the value of x. Also, the statement
*p = 55;
stores 55 in the memory location pointed to by p – that is, in x.

Spring 2024 Data Structure 46


Address of Operator (&)
l In C++, the ampersand, &, called the address of operator, is a unary operator
that returns the address of its operand. For example, given the statements:
int x;
int *p;
the statement:
p = &x;
assigns the address of x to p. That is, x and the value of p refer to the
same memory location.
l Note that when & is used in a declaration (including function formal
parameters), it is part of the type identifier and is used to declare a reference
variable (or reference or alias or alternate name). It is used to provide another
name, or another reference, or alias to an existing variable.
(https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp4_PointerReferenc
e.html)
int x;
int &p = x;
Both x and p refer to the same location. Any value change in x would result in
the same change in p, and vice versa.
Spring 2024 Data Structure 47
Matching of Pointer Types

int k = 10;
float x = 3.15;
int *kPtr = &k; // int pointer pointing to an int variable
float *xPtr = &x; // float pointer pointing to a float variable

xPtr = &k; // Wrong !!


kPtr = &x; // Wrong !!
kPtr = k; // Wrong !!

Spring 2024 Data Structure 48


Examples for Pointer Operations

Spring 2024 Data Structure 49


Examples for Pointer Operations

Spring 2024 Data Structure 50


Classes, Structs, and Pointer Variables

l The only difference between classes and structs is that, by default, all
members of a class are private, and, by default, all members of a
struct are public. Therefore, the following discussion applies to both.
struct studentType
{
char name[26]; pointerVariableName -> classMemberName
double gpa; is equivalent to
int sID; (*pointerVariableName).classMemberName
char grade;
};
studentType student;
studentType* studentPtr;

studentPtr = &student;
(*studentPtr).gpa = 3.9; //Correct
*studentPtr.gpa = 3.9; //Wrong !!! The . has a higher precedence than *
studentPtr->gpa = 3.9; // equivalent to (*studentPtr).gpa = 3.9;
Spring 2024 Data Structure 51
Initializing Pointer Variables

l Because C++ does not automatically initialize variables, pointer


variables must be initialized if you do not want them to point to
anything. Pointer variables are initialized using the constant value 0,
called the null pointer. Thus, the statement p = 0; stores the null
pointer in p; that is, p points to nothing. Some programmers use the
named constant NULL to initialize pointer variables. The following two
statements are equivalent:
p = NULL;
p = 0;
l The number 0 is the only number that can be directly assigned to a
pointer variable.

Spring 2024 Data Structure 52


Dynamic Variables

l Variables that are created during program execution are


called dynamic variables. With the help of pointers, C++
creates dynamic variables. C++ provides two operators,
new and delete, to create and destroy dynamic variables,
respectively. When a program requires a new variable,
the operator new is used. When a program no longer
needs a dynamic variable, the operator delete is used.
l In C++, new and delete are reserved words.

Spring 2024 Data Structure 53


Operator new
new datatype; //to allocate a single variable
new datatype[intExp]; //to allocate an array of variables
in which intExp is any expression evaluating to a positive integer.
l The operator new allocates memory (a variable) of the designated
type and returns a pointer to it—that is, the address of this allocated
memory. Moreover, the allocated memory is uninitialized.

Spring 2024 Data Structure 54


Operator delete

p = new int; //Line 1


*p = 54; //Line 2
p = new int; //Line 3
*p = 73; //Line 4

l What happened to the memory space 1500, to which p was pointing,


before the execution of the statement in Line 3? After execution of the
statement in Line 3, p points to the new memory space at location
1800. The previous memory space at location 1500 is now
inaccessible. In addition, the memory space 1500 remains marked as
allocated. In other words, it cannot be reallocated. This is called
memory leak. That is, there is an unused memory space that cannot
be allocated.
Spring 2024 Data Structure 55
Operator delete

l The question is how to avoid memory leak. When a dynamic variable


is no longer needed, it can be destroyed; that is, its memory can be
deallocated. The C++ operator delete is used to destroy dynamic
variables. The syntax to use the operator delete has two forms:
delete pointerVariable; //to deallocate a single dynamic variable
delete [] pointerVariable; //to deallocate a dynamically created array

delete p;
delete [] name;
delete str;

Spring 2024 Data Structure 56


Operations on Pointer Variables
l Assignment and Comparison: pointers of the same type.
int *p, *q;
p = q; //pointers of the same type.
p == q; //pointers of the same type.
p != q; //pointers of the same type.
l Increment: The increment operator increments the value of a pointer
variable by the size of the data type or structure to which it is pointing.
Similarly, the decrement operator decrements the value of a pointer variable
by the size of the data type or structure to which it is pointing.
int *p;
double *q;
char *chPtr;
studentType *stdPtr;
p++; //increments the value of p by 4 bytes;
q++; //increments the value of p by 8 bytes;
chPtr++; //increments the value of p by 1 bytes;
stdPtr++; //increments the value of p by the # of bytes of studentType Variable
Spring 2024 Data Structure 57
Dynamic Arrays
l An array created during the execution of a program is called a
dynamic array. To create a dynamic array, we use the second form
of the new operator.
int *p;
p = new int[10];
allocates 10 contiguous memory locations, each of type int, and
stores the address of the first memory location into p. In other words,
the operator new creates an array of 10 components of type int, it
returns the base address of the array, and the assignment operator
stores the base address of the array into p. Thus, the statement
*p = 25;
stores 25 into the first memory location, and the statements
p++; Equivalently,
*p = 35; p[0] = 25;
store 35 into the second memory location. p[1] = 35;
Spring 2024 Data Structure 58
Dynamic Two-Dimensional Arrays

int *board[4]; //array of 4 int pointers


// or
// int **board;
// int board = new int* [4];
for (int row = 0; row < 4; row++) //create 4x6 2D array
board[row] = new int [6];

Spring 2024 Data Structure 59


Shallow versus Deep Copy and Pointers
int *first;
int *second;
first = new int [10];
Suppose,

second = first; //Shallow Copy

delete [] second;

second = new int [10];


for (int j = 0; j < 10; j++) //Deep Copy
second[j] = first[j];

Spring 2024 Data Structure 60


Functions and Pointers — Initialization
#include <iostream> void passByValue(int fValue)
#include <cstdlib> { dataA
using namespace std; fValue = fValue + 1;
} 1
int *dataPtr;
0x00A0
void passByRef(int &fRef) p
void passByValue(int fValue); {
0x00A0
void passByRef(int &fRef); fRef = fRef + 1;
void passByPtr(int * fPtr); }
void passByPtrRef(int * &fPtrRef);

int main(int argc, char* argv[]) void passByPtr(int * fPtr)


{ { dataB
int dataA = 1; *fPtr = *fPtr + 1;
int dataB = 5; fPtr = dataPtr; 5
int *p = &dataA; *fPtr = 7;
dataPtr = &dataB; } 0x00B0
dataPtr
passByValue(dataA);
passByRef(dataA); void passByPtrRef(int * &fPtrRef) 0x00B0
passByPtr(p); {
passByPtrRef(p); *fPtrRef = *fPtrRef + 1;
fPtrRef = dataPtr;
return(0); *fPtrRef = 9;
} Spring 2024 } Data Structure 61
Functions and Pointers — Pass by Value
#include <iostream> void passByValue(int fValue) fValue
#include <cstdlib> { dataA
using namespace std; fValue = fValue + 1; 1®2
} 1
int *dataPtr;
0x00A0
void passByRef(int &fRef) p
void passByValue(int fValue); {
0x00A0
void passByRef(int &fRef); fRef = fRef + 1;
void passByPtr(int * fPtr); }
void passByPtrRef(int * &fPtrRef);

int main(int argc, char* argv[]) void passByPtr(int * fPtr)


{ { dataB
int dataA = 1; *fPtr = *fPtr + 1;
int dataB = 5; fPtr = dataPtr; 5
int *p = &dataA; *fPtr = 7;
dataPtr = &dataB; } 0x00B0
dataPtr
passByValue(dataA);
passByRef(dataA); void passByPtrRef(int * &fPtrRef) 0x00B0
passByPtr(p); {
passByPtrRef(p); *fPtrRef = *fPtrRef + 1;
fPtrRef = dataPtr;
return(0); *fPtrRef = 9;
} Spring 2024 } Data Structure 62
Functions and Pointers — Pass by Reference
#include <iostream> void passByValue(int fValue)
#include <cstdlib> { dataA, fRef
using namespace std; fValue = fValue + 1;
} 1®2
int *dataPtr;
0x00A0
void passByRef(int &fRef) p
void passByValue(int fValue); {
0x00A0
void passByRef(int &fRef); fRef = fRef + 1;
void passByPtr(int * fPtr); }
void passByPtrRef(int * &fPtrRef);

int main(int argc, char* argv[]) void passByPtr(int * fPtr)


{ { dataB
int dataA = 1; *fPtr = *fPtr + 1;
int dataB = 5; fPtr = dataPtr; 5
int *p = &dataA; *fPtr = 7;
dataPtr = &dataB; } 0x00B0
dataPtr
passByValue(dataA);
passByRef(dataA); void passByPtrRef(int * &fPtrRef) 0x00B0
passByPtr(p); {
passByPtrRef(p); *fPtrRef = *fPtrRef + 1;
fPtrRef = dataPtr;
return(0); *fPtrRef = 9;
} Spring 2024 } Data Structure 63
Functions and Pointers — Pass by Pointer(1)
#include <iostream> void passByValue(int fValue)
#include <cstdlib> { dataA
using namespace std; fValue = fValue + 1;
} 2®3
int *dataPtr;
0x00A0
void passByRef(int &fRef) p
void passByValue(int fValue); {
0x00A0
void passByRef(int &fRef); fRef = fRef + 1;
void passByPtr(int * fPtr); }
void passByPtrRef(int * &fPtrRef);
fPtr
int main(int argc, char* argv[]) void passByPtr(int * fPtr) 0x00A0
{ { dataB
int dataA = 1; *fPtr = *fPtr + 1;
int dataB = 5; fPtr = dataPtr; 5
int *p = &dataA; *fPtr =7;
dataPtr = &dataB; } 0x00B0
dataPtr
passByValue(dataA);
passByRef(dataA); void passByPtrRef(int * &fPtrRef) 0x00B0
passByPtr(p); {
passByPtrRef(p); *fPtrRef = *fPtrRef + 1;
fPtrRef = dataPtr;
return(0); *fPtrRef = 9;
} Spring 2024 } Data Structure 64
Functions and Pointers — Pass by Pointer(2)
#include <iostream> void passByValue(int fValue)
#include <cstdlib> { dataA
using namespace std; fValue = fValue + 1;
} 3
int *dataPtr;
0x00A0
void passByRef(int &fRef) p
void passByValue(int fValue); {
0x00A0
void passByRef(int &fRef); fRef = fRef + 1;
void passByPtr(int * fPtr); }
void passByPtrRef(int * &fPtrRef);
fPtr
int main(int argc, char* argv[]) void passByPtr(int * fPtr) 0x00B0
{ { dataB
int dataA = 1; *fPtr = *fPtr + 1;
int dataB = 5; fPtr = dataPtr; 5®7
int *p = &dataA; *fPtr = 7;
dataPtr = &dataB; } 0x00B0
dataPtr
passByValue(dataA);
passByRef(dataA); void passByPtrRef(int * &fPtrRef) 0x00B0
passByPtr(p); {
passByPtrRef(p); *fPtrRef = *fPtrRef + 1;
fPtrRef = dataPtr;
return(0); *fPtrRef = 9;
} Spring 2024 } Data Structure 65
Functions and Pointers — Pass by Pointer Ref(1)
#include <iostream> void passByValue(int fValue)
#include <cstdlib> { dataA
using namespace std; fValue = fValue + 1;
} 3®4
int *dataPtr;
0x00A0
void passByRef(int &fRef) p, fPtrRef
void passByValue(int fValue); {
0x00A0
void passByRef(int &fRef); fRef = fRef + 1;
void passByPtr(int * fPtr); }
void passByPtrRef(int * &fPtrRef);

int main(int argc, char* argv[]) void passByPtr(int * fPtr)


{ { dataB
int dataA = 1; *fPtr = *fPtr + 1;
int dataB = 5; fPtr = dataPtr; 7
int *p = &dataA; *fPtr =7;
dataPtr = &dataB; } 0x00B0
dataPtr
passByValue(dataA);
passByRef(dataA); void passByPtrRef(int * &fPtrRef) 0x00B0
passByPtr(p); {
passByPtrRef(p); *fPtrRef = *fPtrRef + 1;
fPtrRef = dataPtr;
return(0); *fPtrRef = 9;
} Spring 2024 } Data Structure 66
Functions and Pointers — Pass by Pointer Ref(2)
#include <iostream> void passByValue(int fValue)
#include <cstdlib> { dataA
using namespace std; fValue = fValue + 1;
} 4
int *dataPtr;
0x00A0
void passByRef(int &fRef) p, fPtrRef
void passByValue(int fValue); {
0x00B0
void passByRef(int &fRef); fRef = fRef + 1;
void passByPtr(int * fPtr); }
void passByPtrRef(int * &fPtrRef);

int main(int argc, char* argv[]) void passByPtr(int * fPtr)


{ { dataB
int dataA = 1; *fPtr = *fPtr + 1;
int dataB = 5; fPtr = dataPtr; 7®9
int *p = &dataA; *fPtr =7;
dataPtr = &dataB; } 0x00B0
dataPtr
passByValue(dataA);
passByRef(dataA); void passByPtrRef(int * &fPtrRef) 0x00B0
passByPtr(p); {
passByPtrRef(p); *fPtrRef = *fPtrRef + 1;
fPtrRef = dataPtr;
return(0); *fPtrRef = 9;
} Spring 2024 } Data Structure 67

You might also like