| C Tutorial | Arrays in C | |||
|
Data types 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[0] and the last is scores[99].
int scores[100];
scores[0] = 13; // set first element scores[99] = 42; // set last element
The
name
of
the
array
refers
to
the
whole
array.
(implementation) it start of the array.
It's a very common error to try to refer to non-existent scores[100] 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.
Multidimensional Arrays The following declares a two-dimensional 10 by 10 array of integers and sets the first and last elements to be 13.
int board [10][10];
board[0][0] = 13; board[9][9] = 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[1][8] comes right before board[1][9] 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[1000];
numbers[0].numerator = 22; /* set the 0th struct fraction */ numbers[0].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[1000], or really anything of the form numbers[...]) will be the type on the left hand side (struct fraction).
Want To Know more with Video ???
|
|