|

You
can initialize a simple array of built-in types,
such as integers and characters, when you first
declare the array. After the array name, you put
an equal sign (=) and a list of comma-separated
values enclosed in braces. For example,
int
IntegerArray[5] = { 10, 20, 30, 40, 50 };
declares
IntegerArray to be an array of five integers. It
assigns IntegerArray[0] the value 10, IntegerArray[1]
the value 20, and so forth.
If
you omit the size of the array, an array just big
enough to hold the initialization is created. Therefore,
if you write
int
IntegerArray[] = { 10, 20, 30, 40, 50 };
you
will create exactly the same array as you did in
the previous example.
If
you need to know the size of the array, you can
ask the compiler to compute it for you. For example,
const
USHORT IntegerArrayLength;
IntegerArrayLength
= sizeof(IntegerArray)/sizeof(IntegerArray[0]);
sets
the constant USHORT variable IntegerArrayLength
to the result obtained from dividing the size of
the entire array by the size of each individual
entry in the array. That quotient is the number
of members in the array.
You
cannot initialize more elements than you’ve declared
for the array. Therefore,
int
IntegerArray[5] = { 10, 20, 30, 40, 50, 60};
generates
a compiler error because you’ve declared a five-member
array and initialized six values. It is legal, however,
to write
int
IntegerArray[5] = { 10, 20};
Although
uninitialized array members have no guaranteed values,
actually, aggregates will be initialized to 0. If
you don’t initialize an array member, its value
will be set to 0.
DO
let the compiler set the size of initialized arrays.
DON’T write past the end of the array. DO
give arrays meaningful names, as you would with
any variable.DO remember that the first member
of the array is at offset 0.
|