Distinguish between arrays and pointers with suitable examples.
An array is a single, preallocated
chunk of contiguous elements (all of the same type), fixed in size and
location. A pointer is a reference to any data element (of a particular type)
anywhere. A pointer must be assigned to point to space allocated elsewhere, but
it can be reassigned (and the space, if derived from malloc, can be resized) at
any time. A pointer can point to an array, and can simulate (along with malloc)
a dynamically allocated array, but a pointer is a much more general data
structure
Due to the so-called equivalence of arrays and pointers, arrays
and pointers often seem interchangeable, and in particular a pointer to a block
of memory assigned by malloc is frequently treated (and can be referenced using
[]) exactly as if it were a true array.
An array is actually a pointer to the 0th element of the array.
Dereferencing the array name will give the 0th element. This gives us a range
of equivalent notations for array access. In the following examples,
arr is an array.
Array Access
|
Pointer Equivalent
|
arr[0]
|
*arr
|
arr[2]
|
*(arr +2)
|
arr[n]
|
*(arr +n)
|
The array is treated as a constant in the function where it is
declared. This means that we can modify the values in the array, but not the
array itself, so statements like arr ++ are illegal, but arr[n] ++ is legal.
Since an array is like a pointer, we can pass an array to a
function, and modify elements of that array without having to worry about
referencing and de-referencing. Since the array is implemented as a hidden
pointer, all the difficult stuff gets done automatically.
A function which expects to be passed an array can declare that
parameter in one of two ways.