You have a map (a plan) of the computer's memory. You need to
find that essential piece of information which is stored at some
unknown location. How will you find it? You need a pointer!
A pointers is a special type of variable which holds the address or
location of another variable. Pointers point to these locations by
keeping a record of the spot at which they were stored. Pointers to
variables are found by recording the address at which a variable is
stored. It is always possible to find the address of a
piece of storage in C using the special &
operator. For instance:
if location
were a float type variable, it would be easy to find
a pointer to it called location_ptr
.
float location;
float *location_ptr,*address;
location_ptr = &(location);
or
address = &(location);
The declarations of pointers look a little strange at first. The
star *
symbol which stands in front of the variable name is C's way of
declaring that variable to be a pointer. The four lines above make two
identical pointers to a floating point variable called location
, one
of them is called location_ptr
and the other is called address. The
point is that a pointer is just a place to keep a record of the
address of a variable, so they are really the same thing.
A pointer is a bundle of information that has two parts. One part is
the address of the beginning of the segment of memory
that holds whatever is pointed to. The other part is the type
of value that the pointer points to the beginning of. This
tells the computer how much of the memory after the beginning
to read and how to interpret it. Thus, if the pointer is of a
type int, the segment of memory returned will be four bytes
long (32 bits) and be interpreted as an integer. In the case
of a function, the type is the type of value that the function
will return, although the address is the address of the
beginning of the function executable.
If, like some modern day programmers, you believe in sanctity of high
level languages, it is probably a source of wonder why anyone
Would ever want to know the address of these variables. Having gone to
the trouble to design a high level language, like C, in which variables
can be given elegant and meaningful names: it seems like a step in the
backward direction to want to be able to find out the exact number of
the memory location at which it is stored! The whole point of variables,
after all, is that it is not necessary to know exactly where information
is really stored. This is not quite fair though. It is certainly rare
indeed when we should want to know the actual number of the memory
location at which something is stored. That would really make the idea
of a high level language a bit pointless. The idea behind pointers is
that a high level programmer can now find out the exact location of a
variable without ever having to know the actual number
involved. Remember:
A pointer is a variable which holds the address of the
storage location for another given variable.