A pointer is a special type of variable that stores the address of another variable in it.
Declaration and Initialization of Pointer variable
A pointer variable points to the same data type and is created with the
* operator. Then the address of another variable is stored in it.
std::string game = "Cricket";// A pointer with the name ptr, that stores the address of gamestd::string* ptr = &game;std::cout << game << "\n"; // Output: Cricketstd::cout << &game << "\n"; // Output of game memory address: 0x6dfed4std::cout << ptr << "\n"; // Output of pointer to game: 0x6dfed4
Dereferencing a pointer means getting the value that a pointer variable is pointing at.
The dereference operator
* is used to get the value stored in the memory location pointed by the pointer:
std::string game = "Cricket"; // Variable declarationstd::string* ptr = &game; // Pointer declarationstd::cout << *ptr << "\n"; // Output of value dereferenced from ptr: Cricket
- Anonymous contributors
Learn C++ on Codecademy
- Anonymous contributorsAnonymous contributors