Memory and memory addressesΒΆ
In this section, we will give you a rather non-detailed and simplified introduction to the concept of the (main) memory of a computer.
All the data handled by a computer is stored in the main memory of the computer. [*] You can think of the memory as a group of numbered cells:
and the processor can store a small amount of data into each of them. One cell is called a memory location, and its index number is called a memory address.
A memory location can contain one byte of data, which is comprised of 8 bits. Usually, however, the memory is handled in parts that are the size of multiples of a byte.
One memory location can store a data element that
can be presented with 8 bits (for example, char
).
In case you need to store
data that is presented with a larger number of bits, you have to use
a suitable amount of consecutive memory locations.
For example, if the elements of the data type int
have 32 bits,
you could save one integer (i.e. its binary form) into
four consecutive memory locations:
Correspondingly, a 64-bit double
could be stored like this:
The examples show you that the same memory locations can store different types of information at different times.
Because all the data is presented as bits in the depths of the computer, you cannot find out what type of data is stored in a memory location only by looking at its contents. This leads us to an old truth: All data needs to have a type in order for us to handle it correctly.
In C++, the definition of a variable is (according to value semantics) a way to name the contents of a memory location. The compiler chooses a location in the memory for a variable, and keeps track of the information on its type and the chosen memory address. Based on the type information, the compiler is able to use the correct machine commands to handle the value of the variable (i.e., the contents of the memory location).
If you are, for example, declaring an integer variable
int number;
the compiler finds the necessary amount of free, consequent
memory locations, and allocates them as the storage of the variable number
:
After this, every time the program code uses the variable number
, it
is interpreted to mean the value located in the memory locations
allocated to it.
For the future, it is important for you to remember these points:
- each memory location is identified with a unique memory address
- the memory location stores the actual data
- the variable is the name for the value stored in the memory location,
and, resulting from that:
- each variable is connected to a memory address (meaning the one storing the value of the variable).
[*] | This is not the whole truth, but at least all the initial data is, at some point, stored in the main memory. |