Scott Gibson Pointers & Dynamic Memory Lecture #1 Office: LAH 103 Email: sgibson@brookdalecc.edu sgib@optonline.net Web: www.brookdalecc.edu/fac/cos/sgibson Phone: (732) 224 2285 1 2 Pre & Co Requisites Pre Requisites COMP 126: Computer Logic and Design Number systems Basic Hardware Basic Program Design COMP 132: Structured Programming in C++ Co Requisite COMP 233: Object Oriented Programming Using C++ 3 Random Access Memory 1 Byte = 8 bits (Binary digits) 2 8 = 256 possible values Location in memory Known as the byte s address Obtainable via the & operator 4 Data Types Atomic Type Sizes Data Representation Number of bytes required Bit pattern Operations supported int short long float double char 32 bits 16 bits 32 bits 32 bits 64 bits 8 bits 5 6 Copyright (c) 2011 Scott L. Gibson 1
Identifiers Operators User defined Must follow C/C++ naming convention Associated with Data type Memory location & returns a memory address First byte of variable sizeof returns a number of bytes Size of data object Size of data type 7 8 Example 1 1 int x = 10; cout << Contents: << x << endl; cout << Size: << sizeof (x) << endl; cout << Location: << &x << endl; system ( pause ); 9 Pointer Variables A variable that holds memory address Definition x Must specify base type Asterisk (*) indicates pointer variable ptr Examples 0x0012FF60??? int* iptr; float *fptr; Must be de referenced to access data 10 10 Address of x: 0x0012FF60 (32256d) Dereferencing Pointers Uses of the * Operator The pointer contains the data object s address Follow the pointer to the data object Use the asterisk (*) before the pointer John Smith 123 Main Street Anytown, NJ 12345 Multiplication distance = speed * time Pointer definition int* ptr; De referencing pointers *ptr = 100; 11 12 Copyright (c) 2011 Scott L. Gibson 2
Initializations Assignment at declaration Address of existing data object Example int data = 15; int* ptr = &data; Always initialize to something NULL Example 1 2 int x = 10; int* ptr = &x; cout << The contents of x: << x << endl; cout << The address of x: << &x << endl; cout << The contents of ptr: << ptr << endl; cout << The address of ptr: << &ptr << endl; cout << The target of ptr: << *ptr << endl; 13 14 Review 1. What does the & operator do? Returns the address of the first byte of the operand 2. How many possible values can an 8 bit hold? 256 3. How is a pointer variable declared? BaseType* ptr; 4. How is a pointer variable de referenced? cout << *ptr; Pointers to Constants Pointers can reference constant data objects Definition const keyword placed before data type const int* cptr; Can point to non constant data objects Cannot change value through constant pointer 15 16 Constant Pointers Contents of pointer variable cannot change Must be initialized at declaration const keyword placed after * int value = 5; int* const ptrc = &value; Can change value through constant pointer Pointer contents cannot change Arrays and Pointers Array name is a constant pointer Arrays can be used like pointers Pointers can be used like arrays Dereferencing pointer = indexing i array Example short numbers [5]; numbers [0] numbers [1] numbers [2] numbers [3] numbers [4] numbers 17 18 Copyright (c) 2011 Scott L. Gibson 3
Pointer Arithmetic Manipulate pointers via math operations Add multiples of the base type s size Example iptr Pointer to integer (integers are 4 bytes) Currently contains 0x7e00 iptr + 1 Evaluates to 0x7e04 Other Pointer Operators Logical operators ==,!=, <, <=, >, >= Simple comparisons betweenbinaryvalues binary Unary & binary addition & subtraction +, ++, +=, = 19 20 Example 1 3 short list [] = 1, 2, 3, 4, 5; for (int i = 0; i < 5; ++i) cout << (list + i) << endl; for (short* p = list; p < &(list [5]); ++p) cout << *ptr << endl; system ("pause"); Pointer Parameters Pass by pointer Similar to pass by reference Implemented with pass by value Arguments become mutable Caller must pass address Function receives pointer to data object Example void DoubleValue (int* n) *n *= 2; 21 22 Allocated at runtime Single data objects Arrays Variable sizes Operators new delete Dynamic Memory Operator: new Allocates dynamic memory Atomic types (i.e., int, float, etc.) Arrays Class Syntax ptr = new datatype; For array, add [dimension] after datatype For class, add (params) after datatype 23 24 Copyright (c) 2011 Scott L. Gibson 4
Operator: delete Review Deallocates dynamic memory Use onlywith new Syntax delete objptr; for arrays, use [] (empty) after delete 5. If an int pointer containing the value 0x5000 has 1 is added to it, what value will it contain? 0x5004 6. Write a statement that dynamically allocates an array of 25 integers. int* array = new int [25]; 25 26 Review Class Member Selection 7. Write a statement that dynamically allocates an instance of class cgameentity using the default constructor. cgameentity* ptr = new cgameentity; 8. De allocate the two pointers above. delete [] array; delete ptr; Using statically declared object Dot member specifier Object.Method (); Using dynamically declared object Arrow member specifier ObjectPtr >Method (); 27 28 #include <iostream> using namespace std; Example 1 4 class cpoint private: int m_x, m_y; public: cpoint () m_x = m_y = 0; cpoint (int x, int y) Set (x, y); cpoint (const cpoint& pt) Set (pt.m_x, pt.m_y); void Set (int x, int y) m_x = x; m_y = y; int GetX () return m_x; int gety () return m_y; void Print (ostream* out) *out << '(' << m_x << ", " << m_y << ')'; ; 29 30 Copyright (c) 2011 Scott L. Gibson 5
int x = rand () % 10; int y = rand () % 10; cpoint* pt = new cpoint (x, y); pt->print (&cout); cout << endl; int size = rand () % 50; cpoint* ptlist = new cpoint [size]; for (int i = 0; i < size; ++i) x = rand () % 10; y = rand () % 10; ptlist [i].set (x, y); int count = 0; for (int i = 0 ; i < size; ++i) ptlist [i].print (&cout); ++count; 31 32 if (count >= 13) cout << endl; count = 0; cout << endl; delete pt; delete [] ptlist; system ("pause"); Data Structures Represent data efficiently Time efficiency: minimizing run time Memory efficiency: minimizing memory usage Demonstrate relationships between data elements Enforce a processing order Model real world problems 33 34 Arrays vs. Linked Lists Fundamental Design Arrays Contiguous storage Random access Fixed size Linked Lists Non contiguous storage Sequential access Expand and contract as needed Series of dynamically allocated nodes Data Link to the next node Single pointer to the first node TopPtr EndPtr (Optional) Data 1 Data 2 Data 3 NULL 35 36 Copyright (c) 2011 Scott L. Gibson 6
Linked List Implementation #include <iostream> using namespace std; class cnode private: int m_data; cnode* m_next; public: cnode (int data) m_data = data; m_next = NULL; void SetData (int data) m_data = data; int GetData () return m_data; void SetNext (cnode* next) m_next = next; cnode* GetNext () return m_next; ; 37 38 class clist private: cnode* m_top; cnode* m_end; int m_size; public: clist () m_size = 0; m_top = m_end = NULL; clist (int data) m_size = 1; m_top = m_end = new cnode (data); ~clist () while (m_size > 0) RemoveFront (); 39 40 void AddFront (int data) cnode* temp = new cnode (data); if (m_size == 0) m_top = m_end = temp; temp->setnext (m_top); m_top = temp; void AddEnd (int data) cnode* temp = new cnode (data); if (m_size == 0) m_top = m_end = temp; m_end->setnext (temp); m_end = temp; ++m_size; ++m_size; 41 42 Copyright (c) 2011 Scott L. Gibson 7
int RemoveFront () if (m_size > 0) int data = m_top->getdata (); if (m_size == 1) delete m_top; m_top = m_end = NULL; cnode* top = m_top; m_top = m_top->getnext (); delete top; --m_size; return data; 43 44 int RemoveEnd () if (m_size > 0) int data = m_end->getdata (); if (m_size == 1) delete m_end; m_top = m_end = NULL; cnode* cur = m_top; while (cur->getnext ()!= m_end) cur = cur->getnext (); delete m_end; m_end = cur; --m_size; return data; 45 46 void PrintAll (ostream& out) cnode* cur = m_top; while (cur!= NULL) out << cur->getdata () << " "; cur = cur->getnext (); out << endl; ; int GetSize () return m_size; bool IsEmpty () return (m_size!= 0); 47 48 Copyright (c) 2011 Scott L. Gibson 8
clist list; for (int i = 0; i < 10; ++i) list.addfront (i*10); list.addend (i*5); list.printall (cout); system ("pause"); Vector Like arrays Homogeneous sequence of data Random access to contents Unlike arrays Might not have a predefined size Able to "grow" as needed 49 50 Vector Implementation Encapsulated in class Pointer to dynamic array size of array Methods Resize array Get array size Assign array element Retrieve array element Summary Memory Bits & bytes Address of operator & Pointers Defining, assigning, and de referencing Star operator * Dynamic Memory Allocating & de allocating 51 52 Assignment #1 Due next week Jan 31 2011 Implement a simple vector class Use a dynamically allocated array Allow assignments and retrievals allow resizing while in use 53 Copyright (c) 2011 Scott L. Gibson 9