Array and Pointer Interchangeability

Pointer Defintion

Pointer variable refers to (or "points to") another value addresss,it means value stored in the computer memory using its memory address.

Poniter Syntax:

``pointer_vaibale = &variable; ``

Array Definition

An array is a collection of data that holds homogeneous values. That means values should be in same type

Array Syntax

``type variable_name[size]``

Array and Pointer Interchangeability

A unique (and potentially confusing) feature of C is its treatment of arrays and pointers. The array-subscript notation `x[i]`can also be used when `x` is a pointer; the interpretation (using pointer arithmetic) is to access the `(i+1)`th of several adjacent data objects pointed to by `x`, counting the object that `x` points to (which is `x[0]`) as the first element of the array.

Formally, `x[i]` is equivalent to `*(x + i)`. Since the type of the pointer involved is known to the compiler at compile time, the address that `x + i` points to is not the address pointed to by `x` incremented by `i` bytes, but rather incremented by `i` multiplied by the size of an element that `x` points to. The size of these elements can be determined with the operator `size of` by applying it to any dereferenced element of `x`, as in `n = sizeof *x` or `n = sizeof x[0]`.

Furthermore, in most contexts (`sizeof` array being a notable exception), the name of an array is automatically converted to a pointer to the array's first element; this implies that an array is never copied as a whole when named as an argument to a function, but rather only the address of its first element is passed. Therefore, although C's function calls use pass-by-value semantics, arrays are in effect passed by reference.

The number of elements in an array `a` can be determined as `sizeof a / sizeof a[0]`, provided that the name is "in scope" (visible).

An interesting demonstration of the remarkable interchangeability of pointers and arrays is shown below. These four lines are equivalent and each is valid C code. Note how the last line contains the strange code `i[x] = 1;`, which has the index variable `i`apparently interchanged with the array variable `x`. This last line might be found in obfuscated C code.

``````x[i] = 1;
*(x + i) = 1;
*(i + x) = 1;
i[x] = 1; /* strange, but correct */``````

There is, however, a distinction to be made between arrays and pointer variables. Even though the name of an array is in most contexts converted to a pointer (to its first element), this pointer does not itself occupy any storage. Consequently, you cannot change what an array "points to", and it is impossible to assign to an array. (Arrays may however be copied using the`memcpy` function, for example.)