60 likes | 196 Vues
Pointers are fundamental in programming, acting as addresses that reference locations in memory. They allow shared access to data, enhance resource efficiency, and facilitate the creation of dynamic data structures like arrays that can grow in size. Understanding the distinction between pointer types and the need for proper memory management is crucial. Uninitialized pointers can lead to errors, and failing to deallocate memory can cause leaks. This guide explores pointer operations, their use in data management, and dynamic allocation, ensuring effective coding practices.
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