In C++, a pointer is a variable that holds the memory address of another variable. Instead of directly storing a value, pointers store the location in memory where the value is kept.
Syntax:
type* pointer_name;
Explanation:
- type is the type of the variable the pointer will point to (e.g., int, char, etc.).
- pointer_name is the name of the pointer variable.
Use of Pointers
1. Pointer Declaration: A pointer is declared by placing an asterisk (*) before the pointer variable’s name.
Example:
int* ptr; // Pointer to an integer
2. Pointer Initialization: A pointer is initialized with the memory address of a variable using the address-of operator (&).
Example:
int num = 10;
int* ptr = # // ptr now stores the address of num
3. Dereferencing: Dereferencing a pointer means accessing the value stored at the memory address the pointer is pointing to. This is done using the asterisk (*).
Example:
int value = *ptr; // Dereferencing ptr to get the value stored at the address it points to
Complete Example:
#include
using namespace std;
int main() {
int num = 10; // A regular integer variable
int* ptr = # // Pointer ptr holds the address of num
cout << "Value of num: " << num << endl; // Output: 10
cout << "Address of num: " << &num << endl; // Output: Memory address of num
cout << "Value pointed to by ptr: " << *ptr << endl; // Output: 10 (value at address ptr points to)
return 0;
}
Output:
Value of num: 10
Address of num: 0x7ffd9f881344
Value pointed to by ptr: 10
Address of num: 0x7ffd9f881344
Value pointed to by ptr: 10