C++ Pointers

C++ Pointers

A pointer is a variable that stores the memory address of another variable as its value. This is one of the most powerful and distinctive features of C++.

The Reference Operator (&)

You can get the memory address of a variable by using the & operator:

Example

string food = "Pizza";
cout << &food; // Outputs the memory address, e.g., 0x6dfed4

Creating Pointers

A pointer variable points to a data type (like int or string) of the same type, and is created with the * operator:

Example

string food = "Pizza";  // A food variable of type string
string* ptr = &food;    // A pointer variable that stores the address of food

// Output the value of food (Pizza) cout << food << "\n";

// Output the memory address of food cout << &food << "\n";

// Output the memory address with the pointer cout << ptr << "\n";

Dereferencing

You can use the pointer to get the value of the variable it points to. This is done by using the * operator again:

Example

cout << *ptr; // Outputs "Pizza"

Pointers are widely used for dynamic memory allocation and building complex data structures like linked lists!


Exercise

?

Which operator is used to get the memory address of a variable?