Topic 38 of 83
Pointers
Overview
A pointer is a variable that stores the memory address of another variable. The asterisk `*` denotes a pointer type.
Syntax
cpp
int x = 10;
int* ptr = &x; // ptr holds the address of x
double pi = 3.14;
double* dPtr = πCommon Pitfalls
- Declaring multiple pointers on one line can be tricky: `int* p1, p2;` makes `p1` a pointer, but `p2` a regular integer. Use `int *p1, *p2;`.
Interview Tips
- The type of the pointer MUST match the type of the variable it points to. An `int*` points to an `int`.
- The size of a pointer itself is dependent on the architecture (usually 8 bytes on a 64-bit system, 4 bytes on a 32-bit system) regardless of what it points to.
Real-World Example
Declaring and initializing pointers safely.
example
cpp
#include <iostream>
using namespace std;
int main() {
int score = 100;
int* scorePtr = &score; // points to score
cout << "Pointer holds address: " << scorePtr << endl;
return 0;
}