Week 7
Week 7
Pointers are one of the most powerful and flexible features in C++. They allow you to directly
interact with memory by storing the memory address of another variable. Understanding pointers
is crucial for dynamic memory management and advanced C++ concepts.
1. Introduction to Pointers
A pointer is a variable that stores the memory address of another variable. The type of the
pointer defines the type of variable it can point to.
Declaring Pointers:
Pointers are declared using an asterisk (*) before the pointer variable name.
Syntax:
Example:
To assign the address of a variable to a pointer, use the address-of operator (&).
Example:
Dereferencing Pointers:
Dereferencing a pointer means accessing the value stored at the memory address the
pointer is pointing to. This is done using the dereference operator (*).
Example:
2. Pointer Arithmetic
Pointer arithmetic is used to navigate through arrays or memory locations by moving the pointer
by a specific number of bytes based on the data type it points to.
Operations on Pointers:
1. Increment (ptr++): Moves the pointer to the next memory address based on the data
type.
2. Decrement (ptr--): Moves the pointer to the previous memory address.
3. Addition (ptr + n): Moves the pointer by n memory locations forward.
4. Subtraction (ptr - n): Moves the pointer by n memory locations backward.
Example:
In C++, you can allocate memory dynamically (at runtime) using the new keyword and
deallocate it using the delete keyword. This is particularly useful when you don't know the size
of an array or the number of objects at compile time.
new is used to allocate memory on the heap for a single variable or an array. It returns the
address of the newly allocated memory.
delete is used to free the memory allocated using new. If you allocate memory using
new[] (for arrays), you should use delete[] to free the memory.
Example:
4. Pointers to Objects
Just like pointers to primitive data types, you can also have pointers to objects in C++. This
allows for dynamic allocation of objects, passing objects to functions by reference, and more
advanced techniques.
Syntax:
Example:
Pointer to Object Arrays:
Example:
Conclusion
Pointers allow direct memory access by holding the address of other variables.
Pointer arithmetic enables moving through memory locations based on the size of the
data type the pointer points to.
Dynamic memory allocation using new and delete is essential for managing memory
efficiently, especially for large datasets or objects whose size is not known at compile
time.
Pointers to objects provide flexibility in handling objects, including dynamic allocation,
and are essential for many advanced C++ techniques.