|C Tutorial||Arrays in C|
The simplest type of array in C is one which is declared and used in one place. There are
more complex uses of arrays which I will address later along with pointers. The following
declares an array called scores to hold 100 integers and sets the first and last elements.
C arrays are always indexed from 0. So the first int in scores array is scores
and the last is scores.
scores = 13; // set first element scores = 42; // set last element
The name of the array refers to the whole array. (implementation) it works by representing a pointer to the
start of the array.
It's a very common error to try to refer to non-existent scores element. C does not do any run time or compile time bounds checking in arrays. At run time the code will just access or mangle whatever memory it happens to hit and crash or misbehave in some unpredictable way thereafter. "Professional programmer's language." The convention of numbering things 0..(number of things - 1) pervades the language. To best integrate with C and other C programmers, you should use that sort of numbering in your own data structures as well.
The following declares a two-dimensional 10 by 10 array of integers and sets the first and
last elements to be 13.
int board ;
board = 13;
board = 13;
The implementation of the array stores all the elements in a single contiguous block of memory. The other possible implementation would be a combination of several distinct one dimensional arrays -- that's not how C does it. In memory, the array is arranged with the elements of the rightmost index next to each other. In other words, board
comes right before board in memory.
(highly optional efficiency point) It's typically efficient to access memory which is near other recently accessed memory. This means that the most efficient way to read through a
chunk of the array is to vary the rightmost index the most frequently since that will access elements that are near each other in memory.
Array of Structs
The following declares an array named "numbers" which holds
1000 struct fraction's.
struct fraction numbers;
numbers.numerator = 22; /* set the 0th struct fraction */
numbers.denominator = 7;
Here's a general trick for unraveling C variable declarations: look at the right hand side and imagine that it is an expression. The type of that expression is the left hand side. For
the above declarations, an expression which looks like the right hand side
(numbers, or really anything of the form numbers[...]) will be the type
on the left hand side (struct fraction).
Want To Know more with