Pointers in C: 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 a points to an array of elements of any type and b points to another element somewhere farther along in the same array, the expression b – a represents the number of elements between these two pointers. For example, if p points 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 x to which p points.4 Therefore, if p is set pointing to the hundredth element in x by a statement such as

p = &x[99];

the value of n after 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 stringLength function from Chapter 10.

In Program 11.15, the character pointer cptr is used to sequence through the charac-

ters pointed to by string until the null character is reached. At that point, string is subtracted from cptr to 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;

while ( *cptr )

++cptr;

return cptr – string;

}

int main (void)

{

int stringLength (const char *string);

printf (“%i “, stringLength (“stringLength test”));

printf (“%i “, stringLength (“”));

printf (“%i\n”, stringLength (“complete”));

return 0;

}

Program 11.15   Output

17 0 8

Source: Kochan Stephen G. (2004), Programming in C: A Complete Introduction to the C Programming Language, Sams; Subsequent edition.

Leave a Reply

Your email address will not be published. Required fields are marked *