chapter 3 pointers and array-based lists dr. youssef harrath

43
Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath [email protected]

Upload: cordelia-scott

Post on 17-Jan-2018

250 views

Category:

Documents


0 download

DESCRIPTION

Declaring Pointer Variables A pointer variable is a variable whose content is an address (memory location). Syntax: dataType *identifier; Example1: int *p; // the content of p pointers to a memory location of the type int Example2: int* p, q; // only p is a pointer variable Example 3: int *p, *q; // both p and q are pointer variables 3 Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

TRANSCRIPT

Page 1: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Chapter 3

Pointers and Array-Based Lists

Dr. Youssef [email protected]

Page 2: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Outline

1. Pointer Data Types and Pointer Variables• Declaring Pointer Variables

• Address of Operator (&)

• Dereferencing Operator (*)

• Classes, structs, and Variables

• Initializing Pointer Variables

• Dynamic Variables

• Operations on Pointer Variables

• Dynamic Arrays

• Function and Pointers

• Classes and Pointers: Some Pecularities

2. Array-Based Lists

2Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

Page 3: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Declaring Pointer Variables

A pointer variable is a variable whose content is an

address (memory location).

Syntax: dataType *identifier;

Example1: int *p; // the content of p pointers to a

memory location of the type int

Example2: int* p, q; // only p is a pointer variable

Example 3: int *p, *q; // both p and q are pointer

variables

3Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

Page 4: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Address of Operator (&)

In C++, the symbol & is a unary operator that returns

the address of its operand.

4Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

int x = 25;

int *p;

p = &x; // assigns the address of x to p, that is x and the value of p

// refer to the same memory location

cout<<*p<<endl; // prints the value pointed by p which is 25

*p = 55; // changes the content of the memory location pointed by

// p, that is x = 55

Page 5: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Dereferencing Operator (*)

5Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

int *p;

int num;

Main Memory

p 1200

num 1800

Main Memory

p 1200

num 1800

Main Memory

p 1200

num 1800

Main Memory

p 1200

num 1800

78

1800

78

1800

24

num = 78; p = &num; *p = 24;

Page 6: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

p 1400

x 1750

Dereferencing Operator (*)

6Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

int *p;

int x;

Main Memory

p 1400

x 1750

Symbol Value

&p 1400

p ???

*p ???

&x 1750

x ???

x = 50;

Main Memory

50

Symbol Value

&p 1400

p ???

*p ???

&x 1750

x 50

Page 7: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

p 1400

x 1750

Dereferencing Operator (*)

7Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

int *p;

int x;

Main Memory

p 1400

x 1750

Symbol Value

&p 1400

p ???

*p ???

&x 1750

x ???

x = 50;

p = &x;

Main Memory

1750

50

Symbol Value

&p 1400

p 1750

*p 50

&x 1750

x 50

Page 8: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

p 1400

x 1750

Dereferencing Operator (*)

8Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

int *p;

int x;

Main Memory

p 1400

x 1750

Symbol Value

&p 1400

p ???

*p ???

&x 1750

x ???

x = 50;

p = &x;

*p = 38;

Main Memory

1750

50

Symbol Value

&p 1400

p 1750

*p 38 50

&x 1750

x 38 50

Page 9: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Classes, structs, and Variables

We can declare and manipulate pointers to other data

types, such as classes.

Both classes and structs have the same capabilities;

the only difference is that, by default, all members of a

class are private and all members of a struct are public.

Therefore, the pointers can be discussed similarly for

classes and structs.

9Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

Page 10: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Classes, structs, and Variables

10Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

struct studentType

{

char name[27];

double gpa;

int sID;

char grade;

};

studentType student; //student is an object of type studentType

studentType* studentPtr; // studentPtr is a pointer variable of the type studentType

studentPtr = &student; // stores the address of student in studentPtr

(*studentPtr).gpa = 3.9; // stores 3.9 in the component gpa of the object student

// equivalent to studentPtr ->gpa = 3.9;

Page 11: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Classes, structs, and Variables

11Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

class classExample{public:

void setX(int a);void print();

private:int x;

};void classExample::setX(int a){

x = a;} void classExample::print(){

cout<<“x = “<<x<<endl;}

int main(){

classExample *cExpPtr; classExample cExpObject;cExpPtr = &cExpObject;cExpPtr ->setX(5);cExpPtr->print(); return 0;

}

Output: x = 5

Page 12: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Initializing Pointer Variables

C++ doesn’t automatically initialize variables.

Pointers must be initialized to avoid them pointing

anything.

p = 0 ; or p = NULL; are equivalent and initialize p to

nothing.

12Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

Page 13: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Dynamic variables

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, respectively, dynamic variables.

13Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

Page 14: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Dynamic variables

14Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

new dataType; // to allocate a single variablenew dataType[intExp]; // to allocate an array of variables

new allocates memory of the desired type and returns a pointer (the address) to it.

int *p;char *q;

int x;p = &x; // store the address of x in p but no new memory is allocated.

p = new int; // allocate memory space of the type int and store the // address of the allocated memory in p.

q = new char[16]; // create an array of 16 char and stores the base address of the array in q.

Page 15: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Dynamic variables

15Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

char *name; // name is a pointer of the type char

name = new char[5]; // allocate memory for an array of 5 char

// elements and stores the base address of the array in name

strcpy(name, “John”); // stores John in name

delete [] name; // destroy the space memory allocated for the array name.

Page 16: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Operations on Pointer Variables

16Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

int *p, *q;

char *ch;

double *d;

p = q; // p and q points to the same memory location. Any changes

// made to *p automatically change the value of *q and vice

versa

if(p ==q) // evaluates to true if p and q point to the same memory location.

if(p!=q) // evaluates to true if p and q point to different memory locations.

p++; // increments the value of p by 4 bytes

d++; // increments the value of p by 8 bytes

ch++; // increments the value of p by 1 byte

Page 17: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Dynamic Arrays

Static arrays have fixed size.

One of the limitations of a static array is that every time you

execute the program, the size of the array is fixed (we have to

change the size whenever we need)

Dynamic arrays are created during the execution.

17Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

Page 18: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Dynamic Arrays

18Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

int *p;

p = new int[10];

*p = 25;

p++;

*p = 35;

Address Valuep 25

p + 4 bytes 35

Page 19: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Functions and Pointers

A pointer variable can be passed as a parameter to a

function either by value or by reference.

19Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

void example(int* &p, double *q)

{

// both p and q are pointers. The parameter p is a

// reference parameter; the parameter q is a value

// parameter

}

Page 20: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Functions and Pointers

In C++ a function can return a value of the type

pointer.

20Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

int* testExp(…)

{

// the returned type of the function is a pointer of the

// type int

}

Page 21: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Classes and Pointers: Some Pecularities

21Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

class pointerDataClass{

public:…

private:int x;

int lenP;int *p;

};pointerDataClass objectOne;pointerDataClass objectTwo;

Page 22: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Classes and Pointers: Some Pecularities

22Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

x

lenP

p

objectOne

x

lenP

p

objectTwo

…p = new int[10]; // dynamic array …

36 …5 24 15

Page 23: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Classes and Pointers: Some Pecularities

23Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

class pointerDataClass{

public:~pointerDataClass(); // destructor to deallocate the dynamic array

// pointed by p…

private:int x;

int lenP;int *p;

};pointerDataClass:: ~pointerDataClass()

{delete [] p;

}

Page 24: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Classes and Pointers: Some Pecularities

24Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

x

lenP

p

objectOne

x

lenP

p

objectTwo

…p = new int[10]; // dynamic array …objectTwo = objectOne;

36 …5 24 15

Problem

If objectTwo.p deallocates

the memory to which it

points, objectOne.p would

become invalid

Solution

Overload the assignment

operator

Page 25: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Classes and Pointers: Some Pecularities

25Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

x

lenP

p

objectOne

x

lenP

p

objectTwo

36 …5 24 15 36 …5 24 15

Page 26: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Classes and Pointers: Some Pecularities

26Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

General Syntax to overload the Assignment Operator (=) for a

Class: const className& operator=()const className&;

const className&::operator=(const className& rightObject){

// local declaration, if anyif(this != &rightObject) // avoid self-assignement

{// algorithm to copy rightObject into this object

}return *this; // return the object assigned

}

Page 27: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Classes and Pointers: Some Pecularities

27Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

Example

Page 28: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Array-Based Lists

A list is a collection of elements of the same type.

The length of a list is the number of elements in the list.

Following are some operations performed on a list:

Create the list. The list is initialized to any empty state.

Determine whether the list is empty.

Determine whether the list is full.

Find the size of the list.

Destroy, or clear, the list.

Insert an item at a given position.

Search the list for a given item.

28Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

Page 29: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Array-Based Lists

Because all the elements of a list are of the same type, they will

be stored in an array.

To process a list in an array, we need the following three

variables:

The array holding the list elements.

A variable to store the length of the list (that is, the number of list

elements currently in the array).

A variable to store the size of the array (that is, the maximum number

of elements that can be stored in the array).

29Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

Page 30: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Array-Based Lists: UML diagram

30Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

arrayListType

#*list: elemType#length: int#maxSize: int

+isEmty(): bool+isFull(): bool+listSize(): int+maxListSize(): int+print() const: void+isItemAtEqual(int, const elemType&): bool+insertAt(int, const elemType&): void+insertEnd(const elemType&): void+removeAt(int): void+retrieveAt(int, elemType&): void+replaceAt(int, const elemType&): void+clearList(): void+seqSearch(const elemType&): int+insert(const elemType&): void+remove(const elemType&): void+arrayListType(int = 100)+arrayListType(const arrayListType<elemType>&)+~arrayListType()+operator=(const arrayListType<elemType>&): const arrayListType<elemType>&

Page 31: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Array-Based Lists: isEmpyt() and isFull()

31Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

template<class elemType>

bool arrayListType<elemType>::isEmpty()

{

return (length == 0);

}

template<class elemType>

bool arrayListType<elemType>::isFull()

{

return (length == maxSize);

}

Page 32: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Array-Based Lists: listSize() and maxListSize()

32Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

template<class elemType>

int arrayListType<elemType>::listSize()

{

return length ;

}

template<class elemType>

int arrayListType<elemType>::maxListSize()

{

return maxSize;

}

Page 33: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Array-Based Lists: print() and isItemAtEqual()

33Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

template<class elemType>void arrayListType<elemType>::print() const

{for(int i = 0; i < length; i++)

cout<<list[i]<<“ “;cout<<endl;

}

template<class elemType>bool arrayListType<elemType>::isItemAtEqual(int location, const elemType& item)

{return(list[location] == item);

}

Page 34: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Array-Based Lists: insertAt()

34Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

template<class elemType>void arrayListType<elemType>::insertAt(int location, const elemType& insertItem)

{if(location < 0 || location >= maxSize)

cerr<<“The position of the item to be inserted is out of range.”<<endl;else

if(length >= maxSize) // the list is fullcout<<“Cannot insert in a full list.<<endl;

else{

for(int i = length; i > location; i--)list[i] = list[i-1]; // shift the elements each one position to the

rightlist[location] = insertItem; // insert the item at the specified position

length++;}

}

Page 35: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Array-Based Lists: insertEnd()

35Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

template<class elemType>

void arrayListType<elemType>::insertEnd(const elemType& insertItem)

{

if(length >= maxSize) // the list if full

cout<<“Cannot insert in a full list.<<endl;

else

{

list[length] = insertItem; // insert the item at the end

length++;

}

}

Page 36: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Array-Based Lists: removeAt()

36Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

template<class elemType>

void arrayListType<elemType>::removeAt(int location)

{

if(location < 0 || location >= length)

cout<<“The location of the item to be removed is out of range.”<<endl;

else

{

for(int i = location; i < length - 1; i++)

list[i] = list[i+1];

length--;

}

}

Page 37: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Array-Based Lists: retrieveAt() and replaceAt()

37Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

template<class elemType>void arrayListType<elemType>::retrieveAt(int location, elemType& retItem)

{if(location < 0 || location >= length)

cout<<“The location of the item to be retrieved is out of range.”<<endl;else

{ retItem = list[location];

}}

template<class elemType>void arrayListType<elemType>::replaceAt(int location, const elemType& repItem)

{if(location < 0 || location >= length)

cout<<“The location of the item to be retrieved is out of range.”<<endl;else

{ list[location] = repItem;

}}

Page 38: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Array-Based Lists: clearList() and arrayListType()

38Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

template<class elemType>void arrayListType<elemType>::clearList()

{length = 0;

}

template<class elemType>arrayListType<elemType>::arrayListType(int size)

{if(size < 0)

{cout<<“The array size must be positive. Creating of an array of size 100.”<<endl;

maxSize = 100;}

elsemaxSize = size;

length = 0;list = new elemType[maxSize];

assert(list != NULL); // capture programming error}

Page 39: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Array-Based Lists: ~arrayListType() and arrayListType()

39Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

template<class elemType>arrayListType<elemType>::~arrayListType() // destructor

{delete [] list;

}

template<class elemType>arrayListType<elemType>::arrayListType(const arrayListType<elemType>& otherList)

{maxSize = otherList.maxSize;

length = otherList.length;list = new elemType[maxSize];

assert(list != NULL); // capture programming error

for(int j = 0; j < length; j++)

list[j] = otherList[j]; }

Page 40: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Array-Based Lists: Overloading the Assignment Operator

40Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

template<class elemType>const arrayListType<elemType>& arrayListType<elemType>::operator=

(const arrayListType<elemType>& otherList){

if(this != &otherList){

delete [] list;maxSize = otherList.maxSize;

length = otherList.length;list = new elemType[maxSize];

assert(list != NULL);for(int i = 0; i < length; i++)

list[i] = otherList.list[i];}

return *this; }

Page 41: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Array-Based Lists: seqSearch()

41Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

template<class elemType>int arrayListType<elemType>::seqSearch(const elemType& item)

{int loc;

bool found = false;for(loc = 0; loc < length; loc++)

if(list[loc] == item){

found = true;break;

}if(found)

return loc;else

return -1;}

Page 42: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Array-Based Lists: insert()

42Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

template<class elemType>void arrayListType<elemType>::insert(const elemType& insertItem)

{ // insert insertItem if it is not in the listint loc;

if(length == 0)list[length++] = insertItem;

elseif(length == maxSize)

cout<<“Cannot insert in a full list.”<<endl;else

{loc = seqSearch(insertItem);

if(loc == -1)list[length++] = insertItem;

elsecout<<“Duplication is not allowed”<<endl;

}}

Page 43: Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath

Array-Based Lists: remove()

43Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

template<class elemType>void arrayListType<elemType>::remove(const elemType& removeItem)

{ int loc;

if(length == 0)cout<<“Cannot remove from an empty list”<<endl;

else{

loc = seqSearch(removeItem);if(loc != -1)

removeAt(loc);else

cout<<“The item to be deleted is not in the list.”<<endl;}}