POINTERS AND MEMORY ACKNOWLEDGEMENT: THE SLIDES ARE PREPARED FROM SLIDES PROVIDED BY NANCY M. AMATO AND JORY DENNY 1
POINTERS Pointers are variables storing the memory address of another data/variable/object. 0x000x040x080x0C0x100x140x180x1C0x20 2
POINTERS Pointers are variables storing the memory address of another data/variable/object. int x=5; 5 x 0x000x040x080x0C0x100x140x180x1C0x20 3
POINTERS AND MEMORY Pointers are variables storing the memory address of another data/variable/object. int x=5; int *y = &x; Operator & gives the memory address of a variable/object 5 xy 0x04 0x000x040x080x0C0x100x140x18 0x1C0x20 4
POINTERS AND MEMORY Pointers are variables storing the memory address of another data/variable/object. int x=5; int *y = &x; Operator & gives the memory address of a variable/object int* z = y; 5 xy 0x04 0x000x040x080x0C0x100x140x18 0x1C0x20 5 z 0x04
POINTERS AND MEMORY int *y = &x; int* z = y; What will happen if I write: *z = 0; ? 5 xy 0x04 0x000x040x080x0C0x100x140x18 0x1C0x20 6 z 0x04
POINTERS AND MEMORY int *y = &x; int* z = y; What will happen if I write: *z = 0; ? * is a dereferencing operator – gives the content of the memory address pointed by (or stored in) the pointer 0 xy 0x04 0x000x040x080x0C0x100x140x18 0x1C0x20 7 z 0x04
MEMORY ALLOCATION – NEW OPERATOR new allocates space to hold the object. new calls the object’s constructor. new returns a pointer to that object. Point * A = new Point (10, 20); 8
MEMORY DEALLOCATION – DELETE OPERATOR For every call to new, there must be exactly one call to delete. Point * A = new Point (10, 20); //allocates memory … delete A; //deallocates or frees the memory 9
POINTERS AND ARRAY An array can act as a pointer Array name is a pointer to first element in the array Pointer can be indexed like an array int arr[5] = {1,2,3,4,5}; cout << arr[2] << "," << *(arr+2); //displays 3,3 10
DYNAMIC ALLOCATION & DEALLOCATION OF ARRAY Static allocation: You must know the size of the array before hand int arr[10]; Dynamic Allocation Size of the array can be passed as a variable size_t sz = 10; int* arr = new int[sz]; Deallocate : delete[] arr; 11
MEMORY 12 MEMORY HEAPSTACK
STACK VS. HEAP Heap – Dynamic Allocation Point *p = new Point(5,10); double *amount = new double[5]; Stack – static allocation Point p(5,10); double amount[5]; 13 What happens when p goes out of scope?
PAIR PROGRAMMING Driver – One at the keyboard Navigator – Helps direct driver Teamwork and communication are key here Switch roles frequently! 14