Programming in C

(Barry) #1
Pointers and Arrays 261

To set textPtrto point to the first character inside the textarray, either the statement

textPtr = text;


or


textPtr = &text[0];


can be used.Whichever statement you choose to use is strictly a matter of taste.
The real power of using pointers to arrays comes into play when you want to
sequence through the elements of an array. If valuesPtris as previously defined and is
set pointing to the first element of values, the expression


*valuesPtr


can be used to access the first integer of the valuesarray, that is,values[0].To refer-
ence values[3]through the valuesPtrvariable, you can add 3 to valuesPtrand then
apply the indirection operator:


*(valuesPtr + 3)


In general, the expression


*(valuesPtr + i)


can be used to access the value contained in values[i].
So, to set values[10]to 27, you could obviously write the expression


values[10] = 27;


or, using valuesPtr,you could write


*(valuesPtr + 10) = 27;


To set valuesPtrto point to the second element of the valuesarray, you can apply the
address operator to values[1]and assign the result to valuesPtr:


valuesPtr = &values[1];


If valuesPtrpoints to values[0],you can set it to point to values[1]by simply
adding 1 to the value of valuesPtr:


valuesPtr += 1;


This is a perfectly valid expression in C and can be used for pointers to anydata type.
So, in general, if ais an array of elements of type x,pxis of type “pointer to x,” and i
and nare integer constants or variables, the statement


px = a;


sets pxto point to the first element of a, and the expression


*(px + i)


subsequently references the value contained in a[i]. Furthermore, the statement


px += n;

Free download pdf