Pointers in C++ - What they are and Memory Addresses (& operator)

In this introductory tutorial to our section on pointers in C++, we will learn the basics of this important concept.

Pointers - What are they? What are worth for? Where they live? What do they feed on?

Pointer is nothing more than a variable, just like int is, like float, double, char etc.
And like every variable, it serves to store a special type of data.
In the case of pointers, these variables are used to store memory addresses.

We are going to use these variables to point to certain memory locations, and work on that.
For example, if we do:

  • int count = 1;


The count variable is stored somewhere in memory, and there is a value of 1.
We could use a pointer to point to the address of this variable. Inside the pointer it does not have the value 1, but a memory address, which points to a location where the 1 is stored.

When we make a statement like this, we are separating a certain amount of kiloBytes in memory to store that value.

Memory addresses: operator &

Still using the example variable, where we use count, C++ replaces it with its value, 1.
For example:

  • cout << count + count;

It will print 1 + 1, that is, 2.

However, it is possible to work with the address, the space in memory, where this number 1 is allocated, instead of working with the value it stores, to do so just use the symbol & before the variable:

  • & count



For example, the code below declares a variable, stores a value.
Then, print the value of the variable, the amount of memory that has been reserved (using the sizeof function, which returns the number of kBytes used) and finally, show its address, using the & operator:

#include <iostream>
using namespace std;

int main()
{
    int count=1;

    cout<<"Variable value  : "<< count << endl;
    cout<<"Size in KB      : "<< sizeof(count) << endl;
    cout<<"Memory address  : "<< &count <<endl;

    return 0;
}

See, on our machine, the int variable uses 4 KB and was stored at the address:


And on your machine?
Now a challenge: how many KB are used to store a memory address?
Write in the comments.

And what does this weird memory address number have to do with a pointer?
Very simple: just as int variables store integers, char variables store characters, etc., pointers are variables that store this thing: memory addresses.

That is, the pointer will point to a memory location, and it is possible to do incredible things with this super simple idea, such as dynamic memory allocation, which we will see later in our C++ course.

No comments:

Post a Comment