C++ Modify Pointers

πŸ”§ C++ Modify Pointers

Modifying pointers in C++ means either:

  1. changing what value a pointer points to (modify data via dereference), or

  2. 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.

int x = 10;
int *p = &x;
*p = 25; // modify value via pointer

cout << x; // 25

βœ” Address same
βœ” Value changed


Β 2. Modify the Pointer to Point to Another Variable

You change the address stored in the pointer.

int a = 10;
int b = 20;
int *p = &a;
p = &b; // pointer now points to b

cout << *p; // 20

βœ” Pointer changed
βœ” Now refers to a different variable


Β 3. Modify Array Elements Using a Pointer

int arr[] = {1, 2, 3};
int *p = arr;
*p = 10; // arr[0] = 10
*(p + 1) = 20; // arr[1] = 20
*(p + 2) = 30; // arr[2] = 30


Β 4. Modify Values in a Loop Using a Pointer

int arr[] = {1, 2, 3, 4};
int *p = arr;
for (int i = 0; i < 4; i++) {
*(p + i) *= 2;
}

Result:

2 4 6 8

Β 5. Modify Value via Pointer in a Function

void update(int *x) {
*x = 100;
}
int a = 10;
update(&a);

cout << a; // 100

βœ” 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.

void setPointer(int **pp, int *newAddr) {
*pp = newAddr;
}
int a = 10, b = 20;
int *p = &a;

setPointer(&p, &b);

cout << *p; // 20


7. Modify Pointer Using Pointer Arithmetic

int arr[] = {10, 20, 30};
int *p = arr;
p++; // move to next element
cout << *p; // 20

➑ Pointer moves by sizeof(int) bytes.


Β 8. Modify Pointer Safely (Using nullptr)

int *p = nullptr;

// later
int x = 5;
p = &x;

βœ” Avoids dangling or garbage pointers


Β 9. What You CANNOT Modify

❌ Reference Address (Not Allowed)

int a = 10, b = 20;
int &r = a;
// r = b; // copies value of b into a, does NOT rebind reference

References cannot be redirected.


❌ Modify Through Pointer to const

const int x = 10;
const int *p = &x;
// *p = 20; ❌ not allowed


πŸ” Common Patterns

Modify Data β†’ use *p

*p = value;

Modify Pointer Target β†’ use p = &var

p = &anotherVar;

Modify Pointer from Function β†’ use **

void f(int **pp) { *pp = newAddr; }

⚠️ Common Mistakes

int *p;
*p = 10; // ❌ uninitialized pointer
int *p = nullptr;
*p = 10; // ❌ dereferencing null pointer

πŸ“Œ Summary

  • *p = value β†’ modifies the data

  • p = &x β†’ modifies where the pointer points

  • Use pointer to pointer to modify a pointer inside a function

  • Be careful with const, nullptr, and initialization

You may also like...