60 likes | 182 Views
Pointers. A pointer is an address All data is stored in memory in some location that is indexed with an address Can refer to variables by name or by memory address Variable name is an alias for the address in memory Purpose of pointers Provide shared access to common data in memory
E N D
Pointers • A pointer is an address • All data is stored in memory in some location that is indexed with an address • Can refer to variables by name or by memory address • Variable name is an alias for the address in memory • Purpose of pointers • Provide shared access to common data in memory • Resource efficiency • Build dynamic data structures • A dynamic array that can grow • Control allocation and de-allocation of memory
Pointers • Pointers are distinguished by the type of pointee • Type double* is not the same as int* • Pointers are uninitialized until assigned • Dereferencing an uninitialized pointer is not a good idea • Dynamic allocation via new • Operator new allocates memory from heap, returns address • Manual de-allocation via delete • Forgetting to delete means memory is orphaned • Accessing deleted memory has unpredictable results
int num; int *p, *q; p = new int; *p = 10; q = new int; *q = *p; q = p; delete p; delete q; //bad idea, q already deleted! q = NULL; //NULL is zero pointer Pointer Operations
Use of Pointers struct studentT { string first, last; string address, phone; }; struct courseT { string dept, name; Vector<studentT *> students; }; • A course has pointers to enrolled students • Allocate studentT record in heap for new student • Each course a student enrolls in will store pointer to that student's record. • Saves space by not repeating student information • If student gets new phone number, it changes in one place only!
Pointers and Dynamic Arrays int *arr = new int[10]; for (int i =0; i < 10; i++) arr[i] = i; delete[ ] arr; Declare a pointer to an array of ten integers Initialize all ten positions Deallocate the array Always use delete[ ] if the array was declared with new
References • see.stanford.edu/materials/icspacs106b/Lecture12.pdf