Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath"— Presentation transcript:

1 Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath yharrath@uob.edu.bh

2 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 2 Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

3 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

4 Address of Operator (&) In C++, the symbol & is a unary operator that returns the address of its operand. 4 Dr. 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

5 Dereferencing Operator (*) 5 Dr. 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;

6 p 1400 x 1750 Dereferencing Operator (*) 6 Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011 int *p; int x; Main Memory p 1400 x 1750 … … … ValueSymbol 1400&p ???p *p 1750&x ???x x = 50; Main Memory … … 50 … ValueSymbol 1400&p ???p *p 1750&x 50x

7 p 1400 x 1750 Dereferencing Operator (*) 7 Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011 int *p; int x; Main Memory p 1400 x 1750 … … … ValueSymbol 1400&p ???p *p 1750&x ???x x = 50; p = &x; Main Memory … 1750 … 50 … ValueSymbol 1400&p 1750p 50*p 1750&x 50x

8 p 1400 x 1750 Dereferencing Operator (*) 8 Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011 int *p; int x; Main Memory p 1400 x 1750 … … … ValueSymbol 1400&p ???p *p 1750&x ???x x = 50; p = &x; *p = 38; Main Memory … 1750 … 50 … ValueSymbol 1400&p 1750p 38 50*p 1750&x 38 50x

9 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. 9 Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

10 Classes, structs, and Variables 10 Dr. 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;

11 Classes, structs, and Variables 11 Dr. 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

12 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. 12 Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

13 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. 13 Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

14 Dynamic variables 14 Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011 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.

15 Dynamic variables 15 Dr. 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.

16 Operations on Pointer Variables 16 Dr. 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

17 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. 17 Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

18 Dynamic Arrays 18 Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011 int *p; p = new int[10]; *p = 25; p++; *p = 35; AddressValue p25 p + 4 bytes35 …

19 Functions and Pointers A pointer variable can be passed as a parameter to a function either by value or by reference. 19 Dr. 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 … }

20 Functions and Pointers In C++ a function can return a value of the type pointer. 20 Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011 int* testExp(…) { // the returned type of the function is a pointer of the // type int … }

21 Classes and Pointers: Some Pecularities 21 Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011 class pointerDataClass { public: … private: int x; int lenP; int *p; }; pointerDataClass objectOne; pointerDataClass objectTwo;

22 Classes and Pointers: Some Pecularities 22 Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011 x lenP p objectOne x lenP p objectTwo … p = new int[10]; // dynamic array … 36 … 52415

23 Classes and Pointers: Some Pecularities 23 Dr. 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; }

24 Classes and Pointers: Some Pecularities 24 Dr. 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 … 52415 Problem If objectTwo.p deallocates the memory to which it points, objectOne.p would become invalid Solution Overload the assignment operator

25 Classes and Pointers: Some Pecularities 25 Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011 x lenP p objectOne x lenP p objectTwo 36 … 5241536 … 52415

26 Classes and Pointers: Some Pecularities 26 Dr. 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 any if(this != &rightObject) // avoid self-assignement { // algorithm to copy rightObject into this object } return *this; // return the object assigned }

27 Classes and Pointers: Some Pecularities 27 Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011 Example

28 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. … 28 Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

29 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). 29 Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011

30 Array-Based Lists: UML diagram 30 Dr. 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 &) +~arrayListType() +operator=(const arrayListType &): const arrayListType &

31 Array-Based Lists: isEmpyt() and isFull() 31 Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011 template bool arrayListType ::isEmpty() { return (length == 0); } template bool arrayListType ::isFull() { return (length == maxSize); }

32 Array-Based Lists: listSize() and maxListSize() 32 Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011 template int arrayListType ::listSize() { return length ; } template int arrayListType ::maxListSize() { return maxSize; }

33 Array-Based Lists: print() and isItemAtEqual() 33 Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011 template void arrayListType ::print() const { for(int i = 0; i < length; i++) cout<<list[i]<<“ “; cout<<endl; } template bool arrayListType ::isItemAtEqual(int location, const elemType& item) { return(list[location] == item); }

34 Array-Based Lists: insertAt() 34 Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011 template void arrayListType ::insertAt(int location, const elemType& insertItem) { if(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(int i = 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++; }

35 Array-Based Lists: insertEnd() 35 Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011 template void arrayListType ::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++; }

36 Array-Based Lists: removeAt() 36 Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011 template void arrayListType ::removeAt(int location) { if(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--; }

37 Array-Based Lists: retrieveAt() and replaceAt() 37 Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011 template void arrayListType ::retrieveAt(int location, elemType& retItem) { if(location = length) cout<<“The location of the item to be retrieved is out of range.”<<endl; else { retItem = list[location]; } template void arrayListType ::replaceAt(int location, const elemType& repItem) { if(location = length) cout<<“The location of the item to be retrieved is out of range.”<<endl; else { list[location] = repItem; }

38 Array-Based Lists: clearList() and arrayListType() 38 Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011 template void arrayListType ::clearList() { length = 0; } template arrayListType ::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 }

39 Array-Based Lists: ~arrayListType() and arrayListType() 39 Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011 template arrayListType ::~arrayListType() // destructor { delete [] list; } template arrayListType ::arrayListType(const arrayListType & 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]; }

40 Array-Based Lists: Overloading the Assignment Operator 40 Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011 template const arrayListType & arrayListType ::operator= (const arrayListType & 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; }

41 Array-Based Lists: seqSearch() 41 Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011 template int arrayListType ::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; }

42 Array-Based Lists: insert() 42 Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011 template void arrayListType ::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; }

43 Array-Based Lists: remove() 43 Dr. Youssef Harrath – University of Bahrain – ITCS 215 – 2010/2011 template void arrayListType ::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; }


Download ppt "Chapter 3 Pointers and Array-Based Lists Dr. Youssef Harrath"

Similar presentations


Ads by Google