C++ Modify Pointers
π§ C++ Modify Pointers
Modifying pointers in C++ means either:
changing what value a pointer points to (modify data via dereference), or
changing where the pointer points (modify the address stored in the pointer).
Below are clear, practical cases.
Β 1. Modify the Value Using a Pointer (Dereferencing)
You keep the pointer pointing to the same address, but change the value at that address.
β Address same
β Value changed
Β 2. Modify the Pointer to Point to Another Variable
You change the address stored in the pointer.
β Pointer changed
β Now refers to a different variable
Β 3. Modify Array Elements Using a Pointer
Β 4. Modify Values in a Loop Using a Pointer
Result:
Β 5. Modify Value via Pointer in a Function
β Call by reference using pointer
6. Modify Pointer Itself in a Function (Pointer to Pointer)
If you want a function to change where a pointer points, use a pointer to pointer.
7. Modify Pointer Using Pointer Arithmetic
β‘ Pointer moves by sizeof(int) bytes.
Β 8. Modify Pointer Safely (Using nullptr)
β Avoids dangling or garbage pointers
Β 9. What You CANNOT Modify
β Reference Address (Not Allowed)
References cannot be redirected.
β Modify Through Pointer to const
π Common Patterns
Modify Data β use *p
Modify Pointer Target β use p = &var
Modify Pointer from Function β use **
β οΈ Common Mistakes
π Summary
*p = valueβ modifies the datap = &xβ modifies where the pointer pointsUse pointer to pointer to modify a pointer inside a function
Be careful with
const,nullptr, and initialization
