Presentation is loading. Please wait.

Presentation is loading. Please wait.

P OINTERS 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.

Similar presentations


Presentation on theme: "P OINTERS 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."— Presentation transcript:

1 P OINTERS 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 P OINTERS 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 P OINTER O PERATIONS 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

4 U SE OF P OINTERS 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! struct studentT { string first, last; string address, phone; }; struct courseT { string dept, name; Vector students; };

5 P OINTERS AND D YNAMIC A RRAYS 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 R EFERENCES see.stanford.edu/materials/icspacs106b/Lecture12.pd f


Download ppt "P OINTERS 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."

Similar presentations


Ads by Google