Pointer-Array relationship
Given an array:
int anArray[10];
if the array identifier
anArray is used
as such, without any brackets
following it, it returns the memory address of the first element of the array.
E.g. the statement:
int *p = anArray;
declares a pointer
p and assigns it the
address of
anArray[0]. Such a statement is
equivalent to the following:
int *p = &anArray[0];
Since an array is a sequence of variables stored in adjacent memory locations,
the array can be run through by incrementing a pointer to it. In the case just
considered:
p++;
would make the pointer point to the second element of the array, i.e.
p will contain
&anArray[1].
Example
#include <iostream>
using namespace std;
int main()
{
int anArray[10];
int *p = anArray;
for(int i = 0; i < 10; i++, p++)
{
*(p) = i;
cout << "anArray[" << i << "] is: "
<< anArray[i] << endl;
}
}
Output
anArray[0] is: 0
anArray[1] is: 1
anArray[2] is: 2
anArray[3] is: 3
anArray[4] is: 4
anArray[5] is: 5
anArray[6] is: 6
anArray[7] is: 7
anArray[8] is: 8
anArray[9] is: 9