How to Modify the pointer value in C++ ?


In C++, we can modify the pointer value in several ways. Here are some methods:

  • Using the dereference operator (): We can modify the value of a pointer by using the dereference operator (). This operator is used to access the value stored at the memory location pointed to by the pointer. We can modify this value by assigning a new value to it.

Example:

int x = 10;
int *ptr = &x; // ptr points to x
*ptr = 20; // modifying the value of x through ptr
cout << x; // output: 20
  • Using the address-of operator (&): We can modify the pointer value itself by using the address-of operator (&). This operator returns the memory address of a variable, which can be assigned to a pointer variable to change its value.

Example:

int x = 10;
int *ptr = &x; // ptr points to x
int y = 20;
ptr = &y; // modifying the value of ptr to point to y
cout << *ptr; // output: 20
  • Using pointer arithmetic: We can modify the pointer value by using pointer arithmetic. Pointer arithmetic allows us to perform arithmetic operations on pointers, such as adding or subtracting an integer value. This can be used to change the memory location pointed to by the pointer.

Example:

int arr[] = {1, 2, 3, 4, 5};
int *ptr = arr; // ptr points to the first element of arr
ptr += 2; // modifying the value of ptr to point to the third element of arr
cout << *ptr; // output: 3

Note: It is important to ensure that the pointer is pointing to a valid memory location before attempting to modify its value. Otherwise, it can lead to undefined behavior.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.