A Pointer variable, just called a pointer, holds the memory address of data that is stored. Through the pointer, you can read the address, and thus indirectly access the value of the variable. To access a value, you use the dereference operators (*) to get the value stored at that memory address.
To store a regular variable, you’d do something like:
int count;
string name;
double radius;
To use a pointer, you’d do the same basic thing, but add the * to the data type. Then you can create a pointer to the variable.
int* pCount;
string* pName;
double* pRadius;
Notice how we put a “p” before each of the variable names? That is to help us identify that these are pointer variables. The data type is still used so that they system knows how big the data is, and how much room to allocate in memory.
To get the memory address of a variable, we would use the ampersand character (&), which is known as the address operator. That way we can assign a variable’s memory address to the pointer. For example:
pCount = &count;
pName = &name;
// don't do this though.
*pCount = &count; // this won't work the way you want it to.
To access the value, we can do things like:
(*pCount)++;
cout << *pName << endl;
You don’t have to use the datatype* variableName convention, there are other ways to declare pointers, but this is the most common. Other ways include:
int * pCount1; // the extra spaces is sometimes confusing, and makes it look like a multiplication.
int *pCount2; // more common than the previous, but usually the original method is used.
Pointer Basics in C++ was originally found on Access 2 Learn