In C, an element of an array is referred to by specifying the array name followed by one or more subscripts, with each sub-script enclosed in square brackets.
- A subscript must be nonnegative integer expression.
- Thus, in an n-element array called x, the array elements are x[0], x[1], …, x[n-1].
- Note that the first element of the array is x[0] and not x[1], as in other programming languages.
The general expression used to access an element of an array is:
array_name[expr]
where expr is an integral expression. expr is called the array subscript, or index and the value of a subscript must lie in the range 0 to size-1, and NOT 1 to size.
Access outside array subscript
An array script value outside the range 0 to size-1 causes a run time error. This is a common programming error called: “over-running the bounds of the array”, or “array out of bounds”
Access Array With Subscript
double x[8] = {16.0, 12.0, 6.0, 8.0, 2.5, 12.0, 14.0, -54.5}; int i=5;
x[4] | has the value 2.5 |
x[i] | has the value 12.0 |
x[i+1] | has the value 14.0 |
x[i*2] | Invalid! Attempt to access x[10] |
x[(int)x[4]]; | has the value 6.0 |
x[i]=x[i+1]; | assigns 14.0 to x[5] |
y = x[i++]; | assigns y the value of x[i], then assigns 6 to i. |
Accessing Array Elements
The control variable in the for loop determines which array element is manipulated during each loop repetition. Each time the value of the loop control variable is increased, the next array element is automatically selected.