🧠 What is a Pointer in C++?
A pointer is like a signpost that shows the address of a variable in memory. 🏷️
Instead of storing a value, it stores the location of that value.
📦 Pointer Basics
*– declares a pointer&– gets the address of a variable*(again) – accesses the value at the address (dereferencing)
🔧 Example: Declare and Use a Pointer
#include <iostream>
using namespace std;
int main() {
int age = 30;
int* ptr = &age;
cout << "Age: " << age << endl;
cout << "Address of age: " << &age << endl;
cout << "Pointer value (address): " << ptr << endl;
cout << "Value using pointer: " << *ptr << endl;
return 0;
}
🎯 Why Use Pointers?
- To access memory directly
- To pass values by reference (efficient!)
- To work with dynamic memory (using
newanddelete)
🛠️ Modify Value via Pointer
Let’s change a value using its pointer.
#include <iostream>
using namespace std;
int main() {
int num = 100;
int* p = #
*p = 200; // Change value through pointer
cout << "Updated value: " << num << endl;
return 0;
}
💡 Summary
- Pointers store memory addresses, not direct values
- Use
&to get the address, and*to access the value - Pointers are essential for reference passing and dynamic memory
Pointers might look tricky, but with a bit of practice, you’ll point like a pro! 🎯