Saturday, October 25, 2008

c: initializing arrays

There various ways to initialize array in c99.

One dimensional array you can initialize just enumerating the values sequentially. Values not initialized explicitly will be initialized with zeros.

int array[3] = {1, 2, 3};
Also you can specify values with designated initializers.
int array[3] = {1, [2] = 3};
In the example above array[0] is 1, array[1] is 0(implicitly initialized) and array[2] is 3.
Multidimensional arrays can be initialized with enumerating the values sequentially.
int array[2][2] = {1, 2, 3, 4};
The values 1, 2, 3, 4 will be assigned to array[0], array[1], array[2], array[3] correspondingly. Grouping the values of the elements of nesting level of elements is more expressive.
int array[2][2] = {{1, 2}, {3, 4}};
As one dimensional arrays multidimensional can be initialized by designated initializers assigning value to each element
int array[2][2] = {[0][0] = 1, [0][1] = 2, [1] = {3, 4}};
or grouping by level
int array[2][2] = {[0] = {1, 2}, [1] = {3, 4}};

No comments: