←to practical programming

Note "pointers"

C-pointers

Suppose we have a variable
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.

Why use pointers in C?

Pointers and arrays

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".

Argument passing

When a C-function is called, it gets the copies of its arguments. This property of the C-language leads to several problems features:

  1. A function cannot change the variables in the caller's scope, since the function gets copies of the variables.
  2. Passing a huge object to a function would unnecessarily create a copy of the object thus wasting resources.
  3. A function in C can only return one value while sometimes you need to return several values and you don't want to create a special object to keep these several values in one variable.

Pointers allow one to overcome these features by passing a pointer to the object instead of the object itself. Indeed,

  1. A copy of a pointer points to the same location, so changing the value at the location changes the value at the caller's scope.
  2. Passing a pointer to an object allows the function to work with the object itself, no need to create a copy of the object.
  3. Passing a pointer to a variable allows the function to return a value by placing it at the pointer's location.