Understanding array elements and pointers
Individual elements of an array can be accessed either with array notation or via pointers.
We have already seen how to access the elements of array
using array notation—[
and ]
, as illustrated in the following code snippet:
array[0] = 1; // first element (zeroth offset)
array[1] = 2;
array[2] = 3;
array[3] = 4;
array[4] = 5; // fifth element (fourth offset)
These statements assign 1..5
values to each element of our array, just as the single initialization statement did when we declared array[5]
.
Accessing array elements via pointers
Arithmetic can be performed with addresses. Therefore, we can access the elements of array
using a pointer plus an offset, as follows:
*(pArray1 + 0) = 1; // first element (zeroth offset)
*(pArray1 + 1) = 2; // second element (first offset...