Programming in C

(Barry) #1

272 Chapter 11 Pointers


Program 11.14 Output
A string to be copied.
So is this.

Operations on Pointers


As you have seen in this chapter, you can add or subtract integer values from pointers.
Furthermore, you can compare two pointers to see if they are equal or not, or if one
pointer is less than or greater than another pointer.The only other operation that is per-
mitted on pointers is the subtraction of two pointers of the same type.The result of sub-
tracting two pointers in C is the number of elements contained between the two point-
ers. So, if apoints to an array of elements of any type and bpoints to another element
somewhere farther along in the same array, the expression b – arepresents the number
of elements between these two pointers. For example, if ppoints to some element in an
array x, the statement
n = p - x;
has the effect of assigning to the variable n(assumed here to be an integer variable) the
index number of the element inside xto which ppoints.^4 Therefore, if pis set pointing
to the hundredth element in xby a statement such as
p = &x[99];
the value of nafter the previous subtraction is performed is 99.
As a practical application of this newly learned fact about pointer subtraction, take a
look at a new version of the stringLengthfunction from Chapter 10.
In Program 11.15, the character pointer cptris used to sequence through the charac-
ters pointed to by stringuntil the null character is reached. At that point,stringis
subtracted from cptrto obtain the number of elements (characters) contained in the
string. The program’s output verifies that the function is working correctly.

Program 11.15 Using Pointers to Find the Length of a String
// Function to count the characters in a string – Pointer version

#include <stdio.h>

int stringLength (const char *string)
{
const char *cptr = string;

4.The actual type of signed integer that is produced by subtracting two pointers (for example,
int,long int, or long long int) is ptrdiff_t, which is defined in the standard header file
<stddef.h>.
Free download pdf