20A. The Memory, Memory Addresses and Pointers


The main memory

The main memory (or simply the memory) is where variables and other information are stored while a program runs. Sometimes it is called the RAM, for random-access memory. From the perspective of a program, the computer's memory is a collection of bytes, each with an integer address. A program can fetch the current contents of the byte at a given memory address and it can store a value into a byte of memory.

A byte is just 8 bits, and most data items 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 on a 32-bit machine, 64 bits on a 64-bit machine.) 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 p has a type that tells the type of value that is in the memory that p points to. To write the type of a pointer, write an asterisk after another type. For example,


Declaring pointer variables

Declare one pointer variable just like you would any other variable: write the variable's type followed by its name. For example,

  int* q;
declares a variable called q of type int*. No initial value is stored into q automatically; q starts out holding a junk pointer, and you need to store a good pointer into q before using it.

If you want to declare two or more pointer variables in one declaration, you need to be aware of a peculiarity of C++: Each variable that is a pointer needs to have a * in front of it. Statement
  char *r, *s;
declares variables r and s, each of type char*. Statement
  char *r, s;
declares variable r of type char* and s of type char. It does not matter where you put spaces. Statement
  char* r, s;
still makes s have type char, not char*.

Declaration

  int a, *b, **c;
says that a has type int, b has type int* and c has type int**.


Exercises

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

  2. How can you declare two variables p and q, each of type int*, in a single declaration? Answer