Principles of Inheritance and Variation: Exhaustive Study Notes
- A pointer is a variable that stores the memory address of another variable.
- In C and C++, pointers are crucial for dynamic memory allocation and data structure manipulation.
- Syntax to declare a pointer:
datatype *pointerName; - Dereferencing a pointer allows you to access or modify the value at the address it points to:
*pointerName. - Pointers can also be used for arrays; the name of an array acts as a pointer to its first element.
- Pointer arithmetic is possible (e.g.,
ptr + 1 moves to the next element based on its data type size). - A null pointer points to nothing:
pointerName = NULL;, indicating that it does not currently reference a valid memory location. - Always ensure pointers are initialized before dereferencing to avoid undefined behavior.
- Common use cases include dynamic array allocation and linked lists.
- In modern C++, consider using smart pointers (
std::unique_ptr, std::shared_ptr) to manage memory automatically and prevent memory leaks.