C++ Pointers

What is a Pointer?

A pointer is a variable that stores the memory address of another variable.

int x = 10;
int* ptr = &x;  // ptr holds address of x

cout << ptr;    // prints memory address
cout << *ptr;   // prints value at address (10)

Declaring a Pointer

Use * in the declaration:

int* p;     // pointer to int
char* cptr;  // pointer to char

& is used to get the address of a variable.

Dereferencing

* is used to access the value pointed to by a pointer:

int val = 50;
int* p = &val;
cout << *p;     // 50

Changing Values via Pointers

int num = 7;
int* p = &num;
*p = 20;
cout << num;    // 20

Modifying *p changes the original variable.

Null Pointer

int* ptr = nullptr;

Always initialize pointers to avoid undefined behavior.

Pointer to Pointer

int a = 5;
int* p = &a;
int** pp = &p;

cout << **pp; // 5

Pointers vs References

  • Pointers can be reassigned; references cannot
  • Pointers can be null; references cannot
  • Pointers require dereferencing explicitly

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic