C++ Pointers Introduction
In this page:
What is a Pointer?
A pointer is a variable whose value is a memory address rather than ordinary data, letting you refer to and manipulate exactly where another variable lives in memory rather than just its value. This indirection is what enables techniques like dynamic memory allocation and passing large data efficiently without copying it.
Example: What is a Pointer?
#include <iostream>
int main() {
int value = 10;
int *ptr = &value;
std::cout << "Address stored: " << ptr << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Declaring and Initializing Pointers
Declaring a pointer places an asterisk between the type and the variable name, like int *ptr;, and the address-of operator & retrieves a variable's actual memory address, so ptr = &age; makes ptr point directly at where age lives in memory.
Example: Declaring and Initializing Pointers
#include <iostream>
int main() {
int value = 42;
int *ptr = &value;
std::cout << *ptr << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Dereferencing Pointers
The dereference operator, also written as * but used differently here — *ptr — accesses or modifies the actual value stored at the address the pointer holds, rather than the address itself. So *ptr = 30; changes the original variable's value through the pointer, not the pointer itself.
Example: Dereferencing Pointers
#include <iostream>
int main() {
int value = 5;
int *ptr = &value;
*ptr = 20;
std::cout << value << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Printing Memory Addresses
Printing a pointer variable directly, without dereferencing it, outputs the memory address it holds — usually shown as a hexadecimal number like 0x7ffee3a1c05c — which is useful for debugging but tells you nothing about the actual value stored at that address unless you dereference it too.
Example: Printing Memory Addresses
#include <iostream>
int main() {
int value = 5;
int *ptr = &value;
std::cout << ptr << std::endl; // prints the address, not the value
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Null Pointers
A pointer that isn't currently pointing at any valid variable should explicitly be set to nullptr rather than left uninitialized, since an uninitialized wild pointer holds a garbage address that could point anywhere in memory. Dereferencing a nullptr still crashes the program, but it does so predictably and is far easier to debug than a wild pointer corrupting unrelated memory.
Example: Null Pointers
#include <iostream>
int main() {
int *ptr = nullptr;
if (ptr == nullptr) {
std::cout << "Pointer is not pointing anywhere yet" << std::endl;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: