#Pointers
2 messages · Page 1 of 1 (latest)
Pointers are typically used when you need to manipulate or reference memory locations directly. They can be useful in cases where you need to pass around large amounts of data, or when you want to modify the original value of a variable inside a function. In C++, you declare a pointer using the * symbol and get its address with the & symbol. Here is an example:
int main() {
int x = 5;
int* ptr = &x;
*ptr = 10; // Changes the value of x to 10
std::cout << "The value of x is: " << x << std::endl;
std::cout << "The value of ptr is: " << ptr << std::endl;
return 0;
}
In this example, we declare an integer variable x with the value of 5. We then declare a pointer ptr to an integer type and initialize it with the address of x using the & symbol. We can then modify the value of x through the pointer ptr by dereferencing it with the * symbol and assigning a new value. Finally, we print out the values of x and ptr to verify that the program worked as expected.