5.10.1. The Memory and Memory Addresses

The main memory

The main memory (or simply the memory) is where variables and other information are stored while a program runs. From the perspective of a program, the computer's memory is a collection of bytes, each with an integer address. For example, there is a byte with address 1, another with address 2, etc., up to a very large number. A program can fetch the current contents of the byte at a given memory address and it can store a given value into that byte.

A byte is just 8 bits. Most of the data items that you use are larger than that. For example, a value of type int is usually 32 bits, so it occupies 4 bytes. A program refers to a block of memory using the address of the first byte in the block. For example, an integer stored in bytes 1000-1003 has address 1000.

Pointers and memory addresses as values

A memory address is called a pointer because you can think of it as pointing to a specific spot in memory.

From a machine language perspective, a pointer is the same as a long integer (32 bits or 64 bits, depending on the type of the executable program). So a program can treat a pointer as information in the same way that it treats an integer as information.

But C++ treats pointers a little differently from the way they are treated in machine language. Each pointer has a type that tells the type of thing in memory that it points to. To write the type of a pointer, write an asterisk after another type. For example,

Getting the address of a variable

If x is a variable then &x is the address where x is stored. So

  int v;
  int* p = &v;
makes variable p hold the address of variable v. Notice that, if v has type T, then &v has type T*.

The null pointer

Memory address 0 is called the null pointer. Your program is never allowed to look at or store anything into memory address 0, so the null pointer is a way of saying "a pointer to nothing". Note that a null pointer is not the same as a null character; do not confuse the two.

Write a null pointer as NULL in your program. For example,

  char* p = NULL;
creates a pointer variable p and makes it hold memory address 0.

It turns out that NULL is not really part of C++. It is added using the preprocessor by defining it in certain header files, including in <cstdio> and <iostream>. To get around that unpleasantness, the newest version of C++ defines a constant nullptr that is the null pointer. But many compilers to not recognize that yet. Please just use NULL.


  1. What sort of thing is stored in a variable of type long*? Answer

  2. Suppose that w is a variable of type long. Write a statement that creates a variable q of type long* and makes q hold the address of variable w. Answer

  3. Are statements

      int r = 0;
      long* p = &r;
    allowed? Answer

  4. Are statements

      long r = 0;
      long* p = r;
    allowed? Answer