Strange array initialize expression?

In C99 you can specify the array indices to assigned value, For example:

static char * name[] = {
   [3]  = "bar"  
};

is same as:

static char * name[] = { NULL, NULL, NULL, "bar"};

The size of array is four. Check an example code working at ideaone. In your code array size is 0x80000001 (its an hexadecimal number).
Note: Uninitialized elements initialized with 0.

5.20 Designated Initializers:

In ISO C99 you can give the elements in any order, specifying the array indices or structure field names they apply to, and GNU C allows this as an extension in C89 mode as well. This extension is not implemented in GNU C++.
To specify an array index, write [index] = before the element value. For example,

 int a[6] = { [4] = 29, [2] = 15 };

is equivalent to

 int a[6] = { 0, 0, 15, 0, 29, 0 };

One more interesting declaration is possible in a GNU extension:

An alternative syntax for this which has been obsolete since GCC 2.5 but GCC still accepts is to write [index] before the element value, with no =.

To initialize a range of elements to the same value, write [first ... last] = value. For example,

 int widths[] = { [0 ... 9] = 1, [10 ... 99] = 2, [100] = 3 }; 

Note: that the length of the array is the highest value specified plus one.

Additionally, we can combine this technique of naming elements with ordinary C initialization of successive elements. Each initializer element that does not have a designator applies to the next consecutive element of the array or structure. For example:

 int a[6] = { [1] = v1, v2, [4] = v4 };

is equivalent to

 int a[6] = { 0, v1, v2, 0, v4, 0 };

Labeling the elements of an array initializer is especially useful when the indices are characters or belong to an enum type. For example:

 int whitespace[256]  = { [' '] = 1,  ['\t'] = 1, ['\h'] = 1,
                          ['\f'] = 1, ['\n'] = 1, ['\r'] = 1 
                        };

Leave a Comment