savitch - chapters 9&11 cs 150173 pointers a pointer holds the memory address of a variable. main...

Download Savitch - Chapters 9&11 CS 150173 Pointers A pointer holds the memory address of a variable. Main Memory Byte #00000000 Byte #00000001 Byte #00000010 Byte

Post on 04-Jan-2016

226 views

Category:

Documents

6 download

Embed Size (px)

TRANSCRIPT

  • Savitch - Chapters 9&11 CS 150*PointersA pointer holds the memory address of a variable.Suppose that x is an int variable that has been placed at this memory location (note that its assumed that an int value requires 4 bytes of memory).In this example, x has the binary value 00000000000000000000000100000101(i.e., 261) and is located at byte #8 (i.e., binary address 00001000).In the program that uses variable x, the pointer to its memory location is accessed by using the & operator: &x is that pointer.

    CS 150

  • Savitch - Chapters 9&11 CS 150*Pointer VariablesA pointer can be stored in a variable.If pointer variable p is declared as follows:int *p;Then p gets the memory address value (in this case 00001000) and the program can access the int value at that address by using the * operator: *p is the int value (in this case 261).Note that pointers to different types of variables are not interchangeable (e.g., if the following declarations occur:int *p; float *q;then p and q are both pointers but they are not the same type of pointers!

    CS 150

  • Savitch - Chapters 9&11 CS 150*A Simple Example#include using namespace std;void main(){ int x = 25; int y = 99; int *p;// At this point, pointer p may be pointing to "illegal" memory! cout
  • Savitch - Chapters 9&11 CS 150*Another Simple Example#include #include using namespace std;void main(){ double *p, *q; double x = 1.357, y = -2.073; cout
  • Savitch - Chapters 9&11 CS 150*The new and delete Operators#include using namespace std;void main(){ int *ptr; cout
  • Savitch - Chapters 9&11 CS 150*The new and delete Operators#include using namespace std;void main(){ char *pointerA; char *pointerB; cout
  • Savitch - Chapters 9&11 CS 150*What About Parameter Passing?#include using namespace std;void reset(int *pp, int qq, int &rr, int *xx, int yy, int &zz);void main(){ int *p, *q, *r; int x = 1, y = 1, z = 1; p = new int; q = new int; r = new int; *p = *q = *r = 1; cout
  • Savitch - Chapters 9&11 CS 150*What About Parameter Passing? (Part Two)

    void reset(int *pp, int qq, int &rr, int *xx, int yy, int &zz){ cout

  • Savitch - Chapters 9&11 CS 150*Static Variables#include using namespace std;void testStatic(int value);void main(){ testStatic(5); return;}void testStatic(int value){ static int count = 1; int zippy = 1; if (value == 0) return; else { cout
  • Savitch - Chapters 9&11 CS 150*Array Variables#include #include using namespace std;void main(){ double a[5] = {0.12345, 1.12345, 2.12345, 3.12345, 4.12345};

    cout.setf(ios::fixed); cout

  • Savitch - Chapters 9&11 CS 150*Dynamic Arrays#include #include using namespace std;void main(){ typedef int* IntPtr; IntPtr intList; int listSize; cout > listSize; intList = new int[listSize]; for (int i = 0; i < listSize; i++) { intList[i] = i; cout
  • Savitch - Chapters 9&11 CS 150*Making The SortedList Class DynamicThe use of the square brackets causes the entire dynamic array to be deleted.// sortedList.h //#ifndef SORTED_LIST_H#include #include #include "phoneListing.h"using namespace std;typedef PhoneListing elementType;typedef elementType* elementTypePtr;class SortedList{ public: SortedList(); SortedList(const SortedList &srtLst); int getLength() const; elementType& operator [ ] (int position); SortedList& operator = (const SortedList &srtLst); bool insert(elementType elt); bool remove(elementType elt); bool retrieve(elementType elt, int &position); private: elementTypePtr entry; int length; int Index(int position) const; bool binarySearch(int firstPosition, int lastPosition, elementType soughtElt, int &position);};#define SORTED_LIST_H#endifNew type definition to make it easier to set up the entry data member as a dynamic array.The revised entry data member.

    CS 150

  • Savitch - Chapters 9&11 CS 150*The Modified Constructors & Assignment Operator

    // This copy constructor sets up the *this SortedList //// as a duplicate of the parameterized SortedList. //SortedList::SortedList(const SortedList &lst){ length = lst.getLength(); entry = new elementType[length]; for (int i = 1; i

  • Savitch - Chapters 9&11 CS 150*The Modified insert & remove Member Functions// This member function inserts the parameterized //// element into the *this SortedList. //bool SortedList::insert(elementType elt){ int position, i; retrieve(elt, position); length++; elementTypePtr tempEntry; tempEntry = new elementType[length]; for (i = 1; i < position; i++) tempEntry[Index(i)] = entry[Index(i)]; tempEntry[Index(position)] = elt; for (i = position+1; i 1) delete [] entry; entry = tempEntry; return true;}// This member function removes the element //// at the parameterized position from the *this //// SortedList (if the position is kosher). //bool SortedList::remove(elementType elt){ int position, i; if (!retrieve(elt, position)) return false; else { length--; elementTypePtr tempEntry; tempEntry = new elementType[length]; for (i = 1; i < position; i++) tempEntry[Index(i)] = entry[Index(i)]; for (i = position; i
  • Savitch - Chapters 9&11 CS 150*Another Dynamic Array Example// This program file tests whether the SortedList class effectively destroys old objects. //#include #include #include #include "sortedList.h" using namespace std;void loadFileWithName(string fileName, elementTypePtr &eltPtr);// The main function repeatedly calls a function that //// loads a SortedList, and outputs the SortedList's //// elements (which should have been destroyed). //void main(){ int soughtValue = 0; int count = 0; elementTypePtr ptrA, ptrB, ptrC, ptrD, ptrE;

    loadFileWithName("fileA.txt", ptrA); loadFileWithName("fileB.txt", ptrB); loadFileWithName("fileC.txt", ptrC); loadFileWithName("fileD.txt", ptrD); loadFileWithName("fileE.txt", ptrE); for (int i = 0; i < 25; i++) cout

  • Savitch - Chapters 9&11 CS 150*Dynamic Arrays Can Waste Memory!When run on the SortedList class (modified to be a list of integers), the driver program wastes memory with each call to the subroutine.While the SortedList variable is not completely destroyed when the function terminates, because the dynamic aspect of the entry data member hasnt been taken into account.All versions of the entry data member are being retained in memory!Of course, theyll all be freed up when the program terminates, but, in the meantime, the memory heap could get filled!

    CS 150

  • Savitch - Chapters 9&11 CS 150*Destructors Solve The Problem!By defining a destructor member function for the SortedList class, we can ensure that a SortedList objects memory is completely returned to the heap once its out of scope (i.e, once the function using it has terminated).The destructor is called for a SortedList variable as the function returns.// Destructor~SortedList();// The destructor function // dereferences the entire // entry array.SortedList::~SortedList(){ if(length > 0) delete [] entry;}Notice that every memory location has been given a value that indicates that its back in the heap!

    CS 150

  • Savitch - Chapters 9&11 CS 150*Copy ConstructorsA copy constructor creates a new object of the designated class, and needs to ensure that the new object is independent of the original being copied.// This copy constructor sets up the *this SortedList //// as a duplicate of the parameterized SortedList. //SortedList::SortedList(const SortedList &lst){ length = lst.getLength(); entry = new elementType[length]; for (int i = 1; i
  • Savitch - Chapters 9&11 CS 150*What If There Was No Copy Constructor?// This program file tests what happens when the //// SortedList class has no copy constructor. //#include #include #include "sortedList.h" using namespace std;void loadList(SortedList srtList, int newVal);// The main function loads a SortedList twice, //// and outputs the SortedList's elements. //void main(){ SortedList list; int i; for (i = 1; i
  • Savitch - Chapters 9&11 CS 150*Assignment OperatorsSimilarly, when an overloaded assignment operator duplicates an object of the designated class, it needs to ensure that the duplicate and original are independent of each other.// The assignment operator gives the *this SortedList duplicate //// values for each data member in the parameterized List. //SortedList& SortedList::operator = (const SortedList &srtLst){ if(entry == srtLst.entry) return *this; delete [] entry; length = srtLst.getLength(); entry = new elementType[length]; for (int i = 1; i

Recommended

View more >