1 / 6

Pointers

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

johnda
Télécharger la présentation

Pointers

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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

  2. 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

  3. 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

  4. 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!

  5. 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

  6. References • see.stanford.edu/materials/icspacs106b/Lecture12.pdf

More Related