Pointers in C++ are variables that store memory addresses, allowing direct access to data locations rather than the data itself.
Retrieving Memory Addresses
To retrieve a variable’s memory address, use the &
(address-of) operator.
Example: Getting the Memory Address of a Variable
C++
x
using namespace std;
int main() {
string motorcycleBrand = "Harley-Davidson";
cout << motorcycleBrand << "\n"; // Outputs Harley-Davidson
cout << &motorcycleBrand << "\n"; // Outputs the memory address (e.g., 0x6dfed4)
return 0;
}
Instead of displaying the value, &motorcycleBrand
prints its memory location.
Creating a Pointer
Pointers store memory addresses rather than direct values. Declare a pointer using the *
(asterisk) operator and assign it the address of another variable.
Example: Assigning a Pointer
C++
using namespace std;
int main() {
string motorcycleBrand = "Harley-Davidson";
string* ptr = &motorcycleBrand; // Pointer storing the address of motorcycleBrand
cout << motorcycleBrand << "\n"; // Outputs Harley-Davidson
cout << &motorcycleBrand << "\n"; // Outputs memory address (e.g., 0x6dfed4)
cout << ptr << "\n"; // Outputs memory address stored in ptr
return 0;
}
Now, ptr
holds the memory address of motorcycleBrand
.
Understanding Pointer Declaration
When declaring a pointer, you may see different formatting styles. All are valid, but string* myString;
is preferred for clarity:
C++
string* myString; // Preferred
string *myString;
string * myString;
The type of the pointer must match the type of the variable it points to.