Modifying Data Using Pointers in C++
Pointers can be used to modify the data of the variables they point to. This is commonly used when passing pointers to functions to allow direct modification of arguments.
Example: Modifying a Variable Using a Pointer
#include <iostream>
void updateValue(int *ptr) {
*ptr = 50;
}
int main() {
int age = 25;
updateValue(&age);
std::cout << "Updated age: " << age << std::endl;
return 0;
}
Explanation: The function updateValue
takes a pointer as an argument and modifies the value at that memory location. In this case, age
is updated to 50.
Key Takeaways
- Pointers allow for modification of variable values indirectly.
- Useful in functions to modify arguments without returning them explicitly.
- Provides efficient ways to manipulate data directly in memory.