Here is an example of how that definition,
A pointer differs from indexing an array in that a pointer also conveys information on the target: the qualified type of the target.
can be very useful in practice: sorting data using the C library
qsort() function.
Let's say you have an array of points, say
typedef struct {
int x;
int y;
} point;
that you want to sort primarily by increasing
y, and points with the same
y coordinates in decreasing
x. All you need to do is write a comparison function,
static int compare_points(const void *ptr1, const void *ptr2)
{
const point *const p1 = ptr1;
const point *const p2 = ptr2;
if (p1->y < p2->y)
return -1; /* Ascending in y */
else
if (p1->y > p2->y)
return +1; /* Ascending in y */
else
if (p1->x < p2->x)
return +1; /* Descending in x */
else
if (p1->x > p2->x)
return -1; /* Descending in x */
else
return 0;
}
and possibly a wrapper function around
qsort() to make the calling easier:
void sort_points(point *const array, const size_t count)
{
if (array && count > 1)
qsort(array, count, sizeof array[0], compare_points);
}
Here, we use a pointer with unspecified/unknown/no target type to refer to the array. The
void type is special; you cannot dereference it (because the target type is unspecified/unknown), but you may cast it to any other (object) pointer type.
Internally,
qsort() only knows the start address of the array, how large each element is in bytes (third parameter), and a function it can call to determine if two elements are in ascending order (
< 0), equal (
0), or in descending order (
> 0). It uses an internal facility similar to
memmove() to swap array elements when needed. It does not need to know what those elements
mean, only how they are ordered. Nifty!
It is very difficult to do the same with array indexing, as evindenced by a lack of a similar routine in Fortran. (Even
sortqq provided by Intel Fortran only works on one-dimensional arrays of base types, not on derived types.)
Of course, the main factor is the comparison function pointer, which allows the one
qsort() function to be used with any type one can imagine, as long as the type has a fixed size, and a comparison function. (If your data type has variable length, for example because it has a flexible array member, you'll typically sort an array of pointers to elements of that type. Which is okay; the comparison function then just receives two pointers to pointers to data.)
Did anyone notice that Simon has long since disappeared from this thread?
I've really tried to help here; it's a pity if the effort is in vain.