Sams Teach Yourself C in 21 Days

(singke) #1
Understanding Pointers 207

9


Decrementing Pointers
The same concepts that apply to incrementing pointers hold true for decrementing point-
ers.Decrementinga pointer is actually a special case of incrementing by adding a nega-
tive value. If you decrement a pointer with the --or-=operators, pointer arithmetic
automatically adjusts for the size of the array elements.
Listing 9.3 presents an example of how pointer arithmetic can be used to access array
elements. By incrementing pointers, the program can step through all the elements of the
arrays efficiently.

LISTING9.3 ptr_math.c. Using pointer arithmetic and pointer notation to access array
elements
1: /* Demonstrates using pointer arithmetic to access */
2: /* array elements with pointer notation. */
3:
4: #include <stdio.h>
5: #define MAX 10
6:
7: /* Declare and initialize an integer array. */
8:
9: int i_array[MAX] = { 0,1,2,3,4,5,6,7,8,9 };
10:
11: /* Declare a pointer to int and an int variable. */
12:
13: int *i_ptr, count;
14:
15: /* Declare and initialize a float array. */
16:
17: float f_array[MAX] = { .0, .1, .2, .3, .4, .5, .6, .7, .8, .9 };
18:
19: /* Declare a pointer to float. */
20:
21: float *f_ptr;
22:
23: int main( void )
24: {
25: /* Initialize the pointers. */
26:
27: i_ptr = i_array;
28: f_ptr = f_array;
29:
30: /* Print the array elements. */
31:
32: for (count = 0; count < MAX; count++)
33: printf(ā€œ%d\t%f\nā€, *i_ptr++, *f_ptr++);
34:
35: return 0;
36: }

15 448201x-CH09 8/13/02 11:21 AM Page 207

Free download pdf