Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 views
in Technique[技术] by (71.8m points)

c - Strange array initialize expression?

What is the meaning of following Code? Code is from the regression test suite of GCC.

static char * name[] = {
   [0x80000000]  = "bar"
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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,  [''] = 1, ['h'] = 1,
                          ['f'] = 1, ['
'] = 1, ['
'] = 1 
                        };

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...