next up previous
Next: Arrays Up: Pointers, Arrays, and References Previous: Pointers, Arrays, and References

Pointers

We declare a to be of type double this way:

   double a;
This declaration reserves 64 bits (8 bytes) of computer memory for storing the value of a. We say that this declaration "allocates storage" for a as well as specifying the datatype to the compiler. In most modern computers each byte has an integer numeric address. In a machine with 32-bit addressing it would take a 32-bit integer to specify the location of the first byte assigned to a. To be concrete and simple, let's say a is assigned bytes $14, 15, \ldots{}, 21$ with the convention that the address of a is given by the address of the first byte, namely 14.

When a is first declared, memory is allocated, but it has no assigned value, which means that its eight bytes of memory could contain nonsense. We assign a value either through an input statement, a subprogram call, or a simple assignment statement:

   a = 5.0;
After this assignment, bytes $14-21$ contain the appropriate double precision binary representation of 5.0.

Pointer variables are for addresses. The compiler distinguishes pointers to different types. Let's define ap to be a pointer to a double:

   double *ap;
In a machine with 32-bit addressing this declaration allocates 32 bits (4 bytes) to the variable ap. So let's say they are bytes $22-25$.

No value is assigned to ap yet. But let's assign it the address of a. Here is how:

   ap = &a;

\framebox{\rm In an expression an ampersand means \lq\lq the address of'' or \lq\lq pointer to''.}
So this is a valid assignment, because the numeric type on both sides is "pointer to a double". The value of ap becomes 14. Figure [*] shows the result of the two declarations and two assignments so far.

\begin{figure}\epsfbox{refs_ptrs_fig1.eps}\end{figure}
The language permits combining assignments and declarations. Here is how:
   double a = 5.0;
   double *ap = &a;
and the result is exactly the same. We say that the variables are ``initialized'' (given initial values) when they are declared. The values don't have to remain constant. They can be given other values at any time.


next up previous
Next: Arrays Up: Pointers, Arrays, and References Previous: Pointers, Arrays, and References
Carleton DeTar 2007-08-17