Sunday, September 26, 2010

Array Initialization in C,C++

C/C++ allows the initialization of arrays at the time of their declaration. The general
form of array initialization is similar to that of other variables, as shown here:
type_specifier array_name[size1]. . .[sizeN] = { value_list };
The value_list is a comma-separated list of values whose type is compatible with
type_specifier. The first value is placed in the first position of the array, the second value
in the second position, and so on. Note that a semicolon follows the }.
In the following example, a 10-element integer array is initialized with the numbers
1 through 10:
int i[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
This means that i[0] will have the value 1 and i[9] will have the value 10.
Character arrays that hold strings allow a shorthand initialization that takes
the form:
char array_name[size] = "string";
For example, this code fragment initializes str to the phrase "I like C++".
char str[11] = "I like C++";
This is the same as writing
char str[11] = {'I', ' ', 'l', 'i', 'k', 'e',' ', 'C',
'+', '+', '\0'};
Because null-terminated strings end with a null, you must make sure that the array you
declare is long enough to include the null. This is why str is 11 characters long even
though "I like C++" is only 10. When you use the string constant, the compiler
automatically supplies the null terminator.
Multidimensional arrays are initialized the same as single-dimension ones. For
example, the following initializes sqrs with the numbers 1 through 10 and their
squares.
int sqrs[10][2] = {
1, 1,
2, 4,
3, 9,
4, 16,
5, 25,
6, 36,
7, 49,
8, 64,
9, 81,
10, 100
};
When initializing a multidimensional array, you may add braces around the
initializers for each dimension. This is called subaggregate grouping. For example, here is
another way to write the preceding declaration.
int sqrs[10][2] = {
{1, 1},
{2, 4},
{3, 9},
{4, 16},
{5, 25},
{6, 36},
{7, 49},
{8, 64},
{9, 81},
{10, 100}
};
When using subaggregate grouping, if you don't supply enough initializers for a
given group, the remaining members will be set to zero automatically.

No comments:

Post a Comment