Pointer Arithmetic
Another facility in C is the use of pointer arithmetic
with which we may change a pointer's value
so that it points to successive memory locations.
We employ pointer arithmetic in the same way that we specify numeric
arithmetic, using ++ and — —
to request
pre- and post- increment and decrement operators.
We generally use pointer arithmetic when
accessing successive elements of arrays.
Consider the following example,
which initializes all elements of an integer array:
#define N 5
int totals[N];
int *p = totals; // p points to the first/leftmost element of totals
for(int i=0 ; i<N ; ++i) {
*p = 0; // set what p points to to zero
++p; // advance/move pointer p "right" to point to the next integer
}
for(int i=0 ; i<N ; ++i) {
printf("address of totals[%i] is: %p\n", i, (void *)&totals[i] );
printf(" value of totals[%i] is: %i\n", i, totals[i] );
}
|
CITS2002 Systems Programming, Lecture 11, p7, 26th August 2024.
|