Week 13 - Chapter 12 Pointers and Arrays Review Quiz 4 ------------- Review Chapter 11 Homework -------------------------- Pointer Arithmetic ------------------ We can use pointers to work with arrays in ways that may seem trivial, because we can often do the same things with array indexes. But there are some advantages to how code looks when using pointers instead of indexes. First, some code: int a[10]; int *p, *q; Normally, when we initialize a pointer variable, we do it by providing the address of a scalar variable. So we can with pointers and the members of an array: p = &a[0]; This code points the p pointer to the beginning of the a array. We can also use a handy shorthand with arrays and pointers that I'll explain more later, and that is to assign the pointer the name of the array itself: p = a; +--+--+--+--+--+--+--+--+--+--+ a | 0| 1| 2| 3| 4| 5| 6| 7| 8| 9| +--+--+--+--+--+--+--+--+--+--+ ^ | p With pointer arithmetic, we can add to and subtract from a point to traverse the array. The pointer is type specific, so if we tell the pointer to add one to itself, it moves right the exact number of bytes it needs to to point to the next member of the array: p++; (move right one cell, point to 1) p+=2; (move right two cells, point to 3) Because the value (p+2) is a pointer value, we can assign values like that to other pointer variables: q = p+2; (q points to 5) And just as we can move right through an array, we can move left, too: q--; (move left one cell, point to 4) Once you have two pointers pointing inside the same array, you can actually do math on the pointers, to learn something about their relation to each other in the array: i = q-p; (1 (4-3)) i = p-q; (-1 (3-4)) Based on this, we can tell which pointer is first in the array: if (p < q) { printf("p is pointing before q\n"); } else if (q > p) { printf("q is pointing before p\n"); } else { printf("p and q are pointing to the same spot\n"); } Using this method, we can traverse an entire array just using pointers: #define NUM 10 total = 0; for (i=0, p = a; i