chapter 3 n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Chapter 3 PowerPoint Presentation
Download Presentation
Chapter 3

Loading in 2 Seconds...

play fullscreen
1 / 43

Chapter 3 - PowerPoint PPT Presentation


  • 161 Views
  • Uploaded on

Chapter 3. Pointers and Array-Based Lists Dr. Youssef Harrath yharrath@uob.edu.bh. Outline. Pointer Data Types and Pointer Variables Declaring Pointer Variables Address of Operator (&) Dereferencing Operator (*) Classes, structs, and Variables Initializing Pointer Variables

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Chapter 3' - niran


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
chapter 3

Chapter 3

Pointers and Array-Based Lists

Dr. YoussefHarrath

yharrath@uob.edu.bh

outline
Outline
  • 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
  • Array-Based Lists

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

declaring pointer variables
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

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

address of operator
Address of Operator (&)
  • In C++, the symbol & is a unary operator that returns the address of its operand.

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

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

dereferencing operator
Dereferencing Operator (*)

Main Memory

Main Memory

Main Memory

Main Memory

int *p;

int num;

num = 78;

p = &num;

*p = 24;

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

dereferencing operator1
Dereferencing Operator (*)

Main Memory

Main Memory

int *p;

int x;

x = 50;

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

dereferencing operator2
Dereferencing Operator (*)

Main Memory

Main Memory

int *p;

int x;

x = 50;

p = &x;

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

dereferencing operator3
Dereferencing Operator (*)

Main Memory

Main Memory

int *p;

int x;

x = 50;

p = &x;

*p = 38;

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

classes structs and variables
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.

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

classes structs and variables1
Classes, structs, and Variables

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;

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

classes structs and variables2
Classes, structs, and Variables

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

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

initializing pointer variables
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.

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

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

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

dynamic variables1
Dynamic variables

new dataType; // to allocate a single variable

new 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.

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

dynamic variables2
Dynamic variables

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.

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

operations on pointer variables
Operations on Pointer Variables

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

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

dynamic arrays
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.

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

dynamic arrays1
Dynamic Arrays

int *p;

p = new int[10];

*p = 25;

p++;

*p = 35;

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

functions and pointers
Functions and Pointers
  • A pointer variable can be passed as a parameter to a function either by value or by reference.

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

}

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

functions and pointers1
Functions and Pointers
  • In C++ a function can return a value of the type pointer.

int* testExp(…)

{

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

// type int

}

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

classes and pointers some pecularities
Classes and Pointers: Some Pecularities

class pointerDataClass

{

public:

private:

int x;

intlenP;

int *p;

};

pointerDataClassobjectOne;

pointerDataClassobjectTwo;

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

classes and pointers some pecularities1
Classes and Pointers: Some Pecularities

objectOne

objectTwo

x

x

lenP

lenP

p

p

p = newint[10]; // dynamic array

5

36

24

15

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

classes and pointers some pecularities2
Classes and Pointers: Some Pecularities

class pointerDataClass

{

public:

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

// pointed by p

private:

int x;

intlenP;

int *p;

};

pointerDataClass:: ~pointerDataClass()

{

delete [] p;

}

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

classes and pointers some pecularities3
Classes and Pointers: Some Pecularities

Problem

If objectTwo.p deallocates the memory to which it points, objectOne.p would become invalid

Solution

Overload the assignment operator

p = newint[10]; // dynamic array

objectTwo = objectOne;

objectOne

objectTwo

x

x

lenP

lenP

p

p

5

36

24

15

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

classes and pointers some pecularities4
Classes and Pointers: Some Pecularities

objectOne

objectTwo

x

x

lenP

lenP

p

p

5

5

36

36

24

24

15

15

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

classes and pointers some pecularities5
Classes and Pointers: Some Pecularities
  • General Syntax to overload the Assignment Operator (=) for a Class: const className& operator=()const className&;

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

{

// local declaration, if any

if(this != &rightObject) // avoid self-assignement

{

// algorithm to copy rightObject into this object

}

return *this; // return the object assigned

}

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

classes and pointers some pecularities6
Classes and Pointers: Some Pecularities

Example

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

array based lists
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.

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

array based lists1
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).

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

array based lists uml diagram
Array-Based Lists: UML diagram

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>&

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

array based lists isempyt and isfull
Array-Based Lists: isEmpyt() and isFull()

template<class elemType>

boolarrayListType<elemType>::isEmpty()

{

return (length == 0);

}

template<class elemType>

boolarrayListType<elemType>::isFull()

{

return (length == maxSize);

}

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

array based lists listsize and maxlistsize
Array-Based Lists: listSize() and maxListSize()

template<class elemType>

intarrayListType<elemType>::listSize()

{

return length ;

}

template<class elemType>

intarrayListType<elemType>::maxListSize()

{

return maxSize;

}

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

array based lists print and isitematequal
Array-Based Lists: print() and isItemAtEqual()

template<class elemType>

void arrayListType<elemType>::print() const

{

for(inti = 0; i < length; i++)

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

cout<<endl;

}

template<class elemType>

boolarrayListType<elemType>::isItemAtEqual(int location, const elemType& item)

{

return(list[location] == item);

}

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

array based lists insertat
Array-Based Lists: insertAt()

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 full

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

else

{

for(inti = length; i > location; i--)

list[i] = list[i-1]; // shift the elements each one position to the right

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

length++;

}

}

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

array based lists insertend
Array-Based Lists: insertEnd()

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++;

}

}

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

array based lists removeat
Array-Based Lists: removeAt()

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(inti = location; i < length - 1; i++)

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

length--;

}

}

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

array based lists retrieveat and replaceat
Array-Based Lists: retrieveAt() and replaceAt()

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;

}

}

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

array based lists clearlist and arraylisttype
Array-Based Lists: clearList() and arrayListType()

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;

}

else

maxSize = size;

length = 0;

list = new elemType[maxSize];

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

}

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

array based lists arraylisttype and arraylisttype
Array-Based Lists: ~arrayListType() and arrayListType()

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];

}

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

array based lists overloading the assignment operator
Array-Based Lists: Overloading the Assignment Operator

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(inti = 0; i < length; i++)

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

}

return *this;

}

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

array based lists seqsearch
Array-Based Lists: seqSearch()

template<class elemType>

intarrayListType<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;

}

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

array based lists insert
Array-Based Lists: insert()

template<class elemType>

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

{ // insert insertItem if it is not in the list

int loc;

if(length == 0)

list[length++] = insertItem;

else

if(length == maxSize)

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

else

{

loc = seqSearch(insertItem);

if(loc == -1)

list[length++] = insertItem;

else

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

}

}

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

array based lists remove
Array-Based Lists: remove()

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;

}

}

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