double x=1.23;The content of this variable is kept in the computer memory at a certain location. One can get the "address of" (or "pointer to") this location,
&x
, using the address-of operator
&
(also called referencing operator).
The object &x
has the type double*
called
"pointer to double". The address can be stored in a variable of type
double*
,
double* p = &x;The variable
p
of the type double*
is called
a pointer (to double). It holds a pointer to the location in
the computer memory where a double
value is kept.
One can extract the double value at that memory location
using the value-at operator *
(also called
dereferencing operator): *p
. Thus *p
is the double value kept in the memory location pointed by the pointer
p
. Therefore,
printf("%g\n",*p);should produce
1.23
.
A copy of the pointer,
double* q = p;points to the same location, so
printf("%g\n",*q);should also produce
1.23
.
Now if one changes the content at the address q
,
*q = 7.0;then both
x
and *p
change to 7.0
as they both refer to the same memory location.
The declaration double* p;
can be also written and
interpreted as double *p;
.
There exist pointers to all types, not only to double.
In the C-language arrays are largely implemented as pointers. Suppose we
declare an array double a[9]
. Then the varible a
has the type double*
and is actually a pointer to the
first element of the array. When an array is passsed as a parameter it
completely becomes a pointer. Therefore the arrays in C do not know
their sizes. The sizes must be passed around together with arrays.
The element indexing operation a[i]
is actually implemented
as *(a+i)
. That is, "the content of the i'th
double
location in the memory counted from a
".
When a C-function is called, it gets the copies of its
arguments. This property of the C-language leads to several
problems features:
Pointers allow one to overcome these features by passing a pointer to the object instead of the object itself. Indeed,