1 <!DOCTYPE HTML PUBLIC
"-//W3O//DTD W3 HTML 2.0//EN">
2 <!-- This collection of hypertext pages is Copyright 1995-7 by Steve Summit. -->
3 <!-- This material may be freely redistributed and used -->
4 <!-- but may not be republished or sold without permission. -->
7 <link rev=
"owner" href=
"mailto:scs@eskimo.com">
8 <link rev=
"made" href=
"mailto:scs@eskimo.com">
9 <title>10.3 Pointer Subtraction and Comparison
</title>
10 <link href=
"sx10b.html" rev=precedes
>
11 <link href=
"sx10d.html" rel=precedes
>
12 <link href=
"sx10.html" rev=subdocument
>
15 <H2>10.3 Pointer Subtraction and Comparison
</H2>
18 you can add an integer to a pointer to get a new pointer,
19 pointing somewhere beyond the original
20 (as long as it's in the same array).
21 For example, you might write
25 Applying a little algebra, you might wonder whether
29 and the answer is, yes.
30 When you subtract two pointers,
31 as long as they point into the same array,
32 the result is the number of elements separating them.
34 (again, as long as they point into the same array)
35 whether one pointer is greater or less than another:
36 one pointer is ``greater than'' another
37 if it points beyond where the other one points.
38 You can also compare pointers for equality and inequality:
39 two pointers are equal
40 if they point to the same variable or to the same cell in an array,
41 and are (obviously) unequal if they don't.
42 (When testing for equality or inequality,
43 the two pointers do not have to point into the same array.)
44 </p><p>One common use of pointer comparisons is when copying arrays
46 Here is a code fragment which copies
10 elements
47 from
<TT>array1
</TT> to
<TT>array2
</TT>, using pointers.
48 It uses an end pointer,
<TT>ep
</TT>,
49 to keep track of when it should stop copying.
51 int array1[
10], array2[
10];
52 int *ip1, *ip2 =
&array2[
0];
53 int *ep =
&array1[
10];
54 for(ip1 =
&array1[
0]; ip1
< ep; ip1++)
58 there is no element
<TT>array1[
10]
</TT>,
60 it is legal to compute a pointer to this (nonexistent) element,
61 as long as we only use it in pointer comparisons like this
63 as long as we never try to fetch or store the value that it points
68 <a href=
"sx10b.html" rev=precedes
>prev
</a>
69 <a href=
"sx10d.html" rel=precedes
>next
</a>
70 <a href=
"sx10.html" rev=subdocument
>up
</a>
71 <a href=
"top.html">top
</a>
74 This page by
<a href=
"http://www.eskimo.com/~scs/">Steve Summit
</a>
75 //
<a href=
"copyright.html">Copyright
</a> 1995-
1997
76 //
<a href=
"mailto:scs@eskimo.com">mail feedback
</a>