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
Interested in helping build Docs? Read the Contribution Guide or share your thoughts in this feedback form.
Learn C++ on Codecademy
Computer ScienceLooking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
Includes 6 Courses
With Professional Certification