Before we talk about pointers, we need to know a little bit more about memory.
Once you write your source code, you can compile it and run it.
This compiled binary will then get loaded from disk into RAM.
The running version of your program is also known as
process. Operating system will usually assign a simplified
version of memory to the process.
That means that your program, the process, can use that assigned long
sequence of bytes to store everything from the space for variables to the
literal instructions that CPU needs to execute.
Of course, all of the details of this implementation depend on the machine's
architecture and operating system, but we will look at this memory in a more
abstract way, and that is okay because languages like C++ exist for a
reason, they allow us to avoid the lowest levels of implementation so that
we can start working on more complicated projects right away, but we still
need to understand the abstraction provided by C++. Let's take a look at
this example.
It is a really simple program, it doesn't really do much.
We are just declaring this X variable has an integer and
storing the number 2 inside of it.
Now let's imagine that this is the memory we were talking about, the piece
of memory that was assigned to your running program.
It looks like a long sequence of storage places,
places where you can store data assigned to variables, and yes,
I did say places on purpose and not bytes because I don't want to
complicate things right at the beginning. When you declare a
variable like this, C++ will pick one of these places which will
serve as a storage for this variable.
Each place in memory has its own memory address which makes sense because
how else would computer know where anything is stored?
For the sake of simplicity, I will choose these
decimal numbers to represent addresses.
Of course, memory is a lot bigger going on and on in both directions.
So let's say that C++ picked this address to store the variable X.
The program will remember that from now on so when you type X,
you are directly referencing this exact place in memory. And
since we have an assignment here,
this number 2 will be stored inside. When we declare variables like this,
we don't care where exactly the storage comes from.
C++ should take care of that.
We only need a place in memory which we can access with the
given identifier, but what if we are for some reason
interested in the address of the variable?
Is there a way to get that information, and yes, you can obtain the
address of a variable by prepending the identifier with the address of
operator, also known as reference operator. In this case, this will
give us back the number 124 and that is all that memory addresses are,
just plain old numbers.
However in practice these numbers are usually a lot bigger and they're
represented in hexadecimal notation. Join me in the next lesson to see this
in practice and how all of this relates to pointers.