本文介绍了在C中使用非标准的数组声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  / *消息类型描述数组* / 
char * msgType [M_LAST_MSG] =
{
[M_INIT_MSG]Init,
[M_RESET_MSG]Serdes Reset
};

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



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

解决方案

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



如果你有这样的话:

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

它相当于这个:

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

在上例中,枚举值指定将数组的元素0和1初始化为InitSerdes Reset

从:

编辑:



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

lockquote

警告:过期使用指定的初始值设定项而不使用'='


GCC文档 a>声明以下内容:


I came across the following code which declares char * array in C in a non-standard way:

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

M_INIT_MSG, M_RESET_MSG and M_LAST_MSG are enumerations with corresponding values of 0, 1 and 2.According to the formal C documentations, the variables inside this array are string (literals) so what is the purpose of using those enumerations in that manner and is there any documentation to back it up?

Compiled with ARM gcc compiler gcc-arm-none-eabi.

This syntax allows you to initialize specific elements of an array by index. You can use either int or enum values to specify which array element to initialize. This way, the values you assign don't need to be consecutive.

If for example you had this:

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

It would be equivalent to this:

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

In the above example, the enum values specify that elements 0 and 1 of the array are initialized to "Init" and "Serdes Reset".

From section 6.7.8 of the C99 standard:

EDIT:

Note that the syntax from the standard includes a = while OP's example does not. The syntax without = is apparently an old syntax supported by GCC. Compiling OP's example gives the following warning:

The GCC documentation states the following:

这篇关于在C中使用非标准的数组声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 16:39
查看更多