DEV Community

Cover image for Simple Explanation of Pointers in C++
May Do
May Do

Posted on

Simple Explanation of Pointers in C++

Every variable has a location in memory and every memory has an address. A pointer is a variable that has the address of another variable. It's denoted by the asterisks symbol (*). So let's take a look at a number variable with the value of 3.

int num = 3;

The address of num would be where the value 3 is located in memory. It's marked with the ampersand symbol (&). If we console log the address, it would look something like this: 0x7ffeeb3989888. The address is going to look like some long line of numbers and letters.

cout << &num; // prints 0x7ffeeb3989888

Now here is the tricky part with pointers. They point to the address of num and also have access to the value of num, but the pointer and num are not the same value. Remember that pointers are only holding the value of the address of num. When we print out the line myPtr, it will print the address of 3.

*myPtr = &num;
cout << myPtr; // prints 0x7ffeeb3989888

But, if we print out *myPtr, it will print out the value of the address. The asterisk symbol will indicate that you are trying to access the variable it points to.

cout << *myPtr; // prints 3

And that's the basic of pointers! It's a simple idea, but easy to get lost in if you don't keep track of what's pointing to what. The most important thing to know is that pointers are not the same as the variable it is pointing to. Pointers are only pointing to the address. For a quick look at what we were doing, this is what the code example looks like:

cout << "Address of num (&num):" << &num << endl; //displays address of num
cout << "myptr value at address (*myptr):" << *myptr << endl; //access the variable it points to
cout << "myptr contents (myptr): " << myptr << endl; //the variable stored in myptr
cout << "myptraddress (&myptr): " << &myptr << endl; //display address of pointer

Top comments (0)