Expert C Programming

(Jeff_L) #1

The most common use of multidimensional arrays in C is to store several strings of characters. Some
people point out that rightmost-subscript-varies-fastest is advantageous for this (adjacent characters in
each string are stored next to each other); this is not true for multidimensional arrays of characters in
leftmost-subscript-varies-fastest order.


How to Initialize Arrays


In the simplest case, one-dimensional arrays can be given an initial value by enclosing the list of
values in the usual curly braces. As a convenience, if you leave out the size of the array, it creates it
with the exact size to hold that number of initial values.


float banana [5] = { 0.0, 1.0, 2.72, 3.14, 25.625 };


float honeydew[] = { 0.0, 1.0, 2.72, 3.14, 25.625 };


You can only assign to an entire array during its declaration. There's no good reason for this restriction.


Multidimensional arrays can be initialized with nested braces:


short cantaloupe[2][5] = {


{10, 12, 3, 4, -5},


{31, 22, 6, 0, -5},


};


int rhubarb[][3] ={ {0,0,0}, {1,1,1}, };


Note that you can include or omit that comma after the last initializer. You can also omit the most
significant dimension (only the most significant dimension), and the compiler will figure it out from
the number of initializers given.


If the array dimension is bigger than the number of initial values provided, the remaining elements are
set to zero. If they are pointers they are set to NULL. If they are floating point elements, they are set to
0.0. In the popular IEEE 754 standard floating point implementation, as used on the IBM PC and Sun
systems, the bit pattern for 0.0 is the same as integer zero in any case.


Programming Challenge

Free download pdf