...

/

What are Pointers?

What are Pointers?

Learn about pointers in C++.

A pointer is a special kind of variable that stores the address in memory of another variable and can be used to manipulate that variable. In general, whenever a variable is used in C++, it must exist somewhere in the host computer’s memory, and pointers can store the location of a particular variable.

Press + to interact

What do pointers hold?

Pointers associate two pieces of information:

  • The memory address, which is the “value” of the pointer itself.

  • The data type of the variable being pointed to, which refers to the type of variable located at that address.

1.

Suppose we have a pointer variable that points to a char variable. What would be the size of this pointer? This pointer later on starts pointing to an int variable. What would be its size now?

Show Answer
Q1 / Q1
Did you find this helpful?

Declaring pointers

Declaring a pointer is easy. You specify its data type, add an asterisk (*), give it a name, and end the line of code with a semicolon.

Press + to interact
int var;
int *var_pointer;

Here, var is an integer variable and var_pointer is a pointer to an integer. It’s not necessary to always initialize a pointer to a variable. We can also initialize a pointer with a null pointer: nullptr to indicate that they are not currently pointing to any memory location. This is a good practice to avoid undefined behavior.

Note: Creating a pointer doesn’t automatically create storage where it points to. Instead, it will start pointing to a location when we assign it an address of a pointer.

Press + to interact
int *var_pointer = nullptr;

Pointer operators

Now that we’ve learned what pointers are and how to initialize them. Let’s see how we can use them. We ...