C++ Modify Pointers



In C++ programming, a pointer is a variable that stores the memory address of another variable. Instead of holding a data value directly, a pointer holds the memory location of the value.

What is Modifying Pointers in C++?

Modifying the pointer value in C++ refers to the process of changing the memory address or changing the value stored at the memory address the pointer is pointing to.

Approach to Modify Pointers

Begin with declaring a pointer variable and initializing it. To modify the pointer's value, assign a new address to it. If using dynamic memory, allocate new memory using new and assign its address to the pointer. After modifying the pointer, you can dereference it to access or modify the value at the new address.

If you allocate memory dynamically, ensure to release it using delete to prevent memory leaks.

Example of Modifying Pointers

Here's a simple example illustrating the modification of the pointers values −

 #include <iostream> using namespace std; int main() { int var1 = 10; int var2 = 20; int* ptr = &var1; // ptr points to var1 cout << "Value pointed by ptr: " << *ptr << endl; ptr = &var2; // Modify ptr to point to var2 cout << "Value pointed by ptr after modification: " << *ptr << endl; // Dynamic memory allocation int* dynamicPtr = new int(30); ptr = dynamicPtr; // Modify ptr to point to dynamic memory cout << "Value pointed by ptr after dynamic allocation: " << *ptr << endl; // Clean up dynamic memory delete dynamicPtr; return 0; } 

Output

 Value pointed by ptr: 10 Value pointed by ptr after modification: 20 Value pointed by ptr after dynamic allocation: 30 

Explanation

  • Firstly, we declared (var1 and var2) and initialized the variable with values 10 and 20.
  • Then declared the pointer named ptr, which holds the address of an integer, var1 using the address-of operator (&).
  • *ptr, the value at the address stored in ptr is accessed using the dereference operator (*).
  • ptr = &var2; The pointer ptr is modified to point to var2. Now, when dereferenced, it will access the value of var2, which is 20, so this prints 20.
  • Now for Dynamic Memory Allocation, int* dynamicPtr = new int(30); Memory is dynamically allocated using new and initialized to 30, Where the address of this memory is stored in the pointer dynamicPtr.
  • ptr = dynamicPtr; in this ptr is modified to point to the dynamically allocated memory (dynamicPtr). When dereferenced, it will print 30.
  • delete dynamicPtr; This is used to prevent memory leaks.
Advertisements
close