c - 在 C 中使用非标准的数组声明

标签 c arrays gcc

我遇到了以下代码,它以非标准方式在 C 中声明了 char * 数组:

    /* Message Type description array */ 
    char *msgType[M_LAST_MSG] = 
    {    
       [M_INIT_MSG]     "Init", 
       [M_RESET_MSG]    "Serdes Reset"
    };

M_INIT_MSGM_RESET_MSGM_LAST_MSG是枚举,对应值为0、1、2。 根据正式的 C 文档,这个数组中的变量是字符串(文字),那么以这种方式使用这些枚举的目的是什么,是否有任何文档来支持它?

使用 ARM gcc 编译器 gcc-arm-none-eabi 编译。

最佳答案

此语法允许您通过索引初始化数组的特定元素。您可以使用 intenum 值来指定要初始化的数组元素。这样,您分配的值就不需要是连续的。

例如,如果你有这个:

int x[5] = { [2] 3, [4] 7 };

这相当于:

int x[5] = { 0, 0, 3, 0, 7 };

在上面的示例中,枚举值指定数组的元素 0 和 1 被初始化为 "Init""Serdes Reset"

来自 C99 standard 的第 6.7.8 节:

18 Each designator list begins its description with the current object associated with the closest surrounding brace pair. Each item in the designator list (in order) specifies a particular member of its current object and changes the current object for the next designator (if any) to be that member. The current object that results at the end of the designator list is the subobject to be initialized by the following initializer.

33 EXAMPLE 9 Arrays can be initialized to correspond to the elements of an enumeration by using designators:

enum { member_one, member_two };
const char *nm[] = {
    [member_two] = "member two",
    [member_one] = "member one",
};

编辑:

请注意,标准中的语法包含 = 而 OP 的示例不包含。没有 = 的语法显然是 GCC 支持的旧语法。编译 OP 的示例会给出以下警告:

warning: obsolete use of designated initializer without ‘=’

GCC documentation陈述如下:

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

关于c - 在 C 中使用非标准的数组声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38721421/

相关文章:

c - dylib 中的符号,适用于 gcc-4.0,不适用于 gcc-4.2(OSX 默认)

c - 为什么用 1 和 0 初始化数组会使可执行文件如此之大?

c++ - GCC 与 Clang : Meaning of "-pedantic-errors"

c - 如何在服务器端使用 openssl 完全禁用重新协商(重新握手)?

c - C 中线程特定数据的示例

c - fopen() 返回 "No such file or directory"

c - 用于调试我的操作系统的调试器

ruby-on-rails - rails postgres 从数据库中读取数组

Javascript将对象的字符串化数组转换为对象数组

Java数组删除困惑?