在c语言中声明时按索引分配数组

时间:2022-09-02 21:23:40
void fun ()
{
    int i;
    int a[]=
    {
    [0]=3,
    [1]=5
    };
}

Does the above way of a[] array assignment is supported in c language. if yes which c version.
i compiled above code with gcc it works fine.

c语言是否支持上述[]数组赋值方式。如果是哪个C版本。我使用gcc编译上面的代码它工作正常。

but i never saw this kind of assignment before.

但我以前从未见过这种作业。

3 个解决方案

#1


5  

This is GCC extension to C89, part of standard in C99, called 'Designated initializer'.

这是C89的GCC扩展,是C99标准的一部分,称为“指定初始化程序”。

See http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Designated-Inits.html.

#2


5  

Must be compiled using gcc -std=c99 or above, otherwise you get:

必须使用gcc -std = c99或更高版本编译,否则你得到:

warning: x forbids specifying subobject to initialize

GNU C allows this as an extension in C89, to skip this warning when -pedantic flag is on you can use __extension__

GNU C允许这作为C89中的扩展,当-pedantic标志打开时跳过此警告可以使用__extension__

void fun ()
{
    int i;
    __extension__ int a[]=
    {
        [0]=3,
        [1]=5
    };
}

#3


2  

From the GNU C Reference Manual:

从GNU C参考手册:

When using either ISO C99, or C89 with GNU extensions, you can initialize array elements out of order, by specifying which array indices to initialize. To do this, include the array index in brackets, and optionally the assignment operator, before the value. Here is an example:

使用带有GNU扩展的ISO C99或C89时,可以通过指定要初始化的数组索引来无序地初始化数组元素。要执行此操作,请在值前包括括号中的数组索引以及可选的赋值运算符。这是一个例子:

 int my_array[5] = { [2] 5, [4] 9 };

Or, using the assignment operator:

或者,使用赋值运算符:

 int my_array[5] = { [2] = 5, [4] = 9 };

Both of those examples are equivalent to:

这两个例子都相当于:

 int my_array[5] = { 0, 0, 5, 0, 9 };

#1


5  

This is GCC extension to C89, part of standard in C99, called 'Designated initializer'.

这是C89的GCC扩展,是C99标准的一部分,称为“指定初始化程序”。

See http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Designated-Inits.html.

#2


5  

Must be compiled using gcc -std=c99 or above, otherwise you get:

必须使用gcc -std = c99或更高版本编译,否则你得到:

warning: x forbids specifying subobject to initialize

GNU C allows this as an extension in C89, to skip this warning when -pedantic flag is on you can use __extension__

GNU C允许这作为C89中的扩展,当-pedantic标志打开时跳过此警告可以使用__extension__

void fun ()
{
    int i;
    __extension__ int a[]=
    {
        [0]=3,
        [1]=5
    };
}

#3


2  

From the GNU C Reference Manual:

从GNU C参考手册:

When using either ISO C99, or C89 with GNU extensions, you can initialize array elements out of order, by specifying which array indices to initialize. To do this, include the array index in brackets, and optionally the assignment operator, before the value. Here is an example:

使用带有GNU扩展的ISO C99或C89时,可以通过指定要初始化的数组索引来无序地初始化数组元素。要执行此操作,请在值前包括括号中的数组索引以及可选的赋值运算符。这是一个例子:

 int my_array[5] = { [2] 5, [4] 9 };

Or, using the assignment operator:

或者,使用赋值运算符:

 int my_array[5] = { [2] = 5, [4] = 9 };

Both of those examples are equivalent to:

这两个例子都相当于:

 int my_array[5] = { 0, 0, 5, 0, 9 };