简体   繁体   English

C数组结构声明

[英]C array of structs declaration

In the Linux kernel, I see a declaration of an array of structs that looks like this 在Linux内核中,我看到一个结构数组的声明,看起来像这样

struct SomeStructName [] ={
[SOMEWEIRD_NAME] = {
                   .field1 = "some value"
                   },
[SOMEWEIRD_NAME2] = {
                   .field1 = "some value1"
                   },
}

I have never seen a declaration like that, specifically I can't figure out what [SOMEWEIRD_NAME] means, and why it's used. 我从未见过这样的声明,特别是我无法弄清楚[SOMEWEIRD_NAME]含义,以及为什么使用它。

It's a C99 designated initializer for arrays. 它是C99 指定的数组初始化器。

For example: 例如:

/* 
 * Initialize element  0 to 1
 *                     1 to 2
 *                     2 to 3
 *                   255 to 1   
 * and all other elements to 0
 */
int arr[256] = {[0] = 1, 2, 3, [255] = 1};

It allows you to initialize some specific array elements in any order and also allows you to omit some elements. 它允许您以任何顺序初始化某些特定的数组元素,并允许您省略一些元素。

In your example the expression between [] can be a macro name for an integer constant expression or an enum constant. 在您的示例中, []之间的表达式可以是整数常量表达式的enum名称或enum常量。 It cannot be a variable name as it has to be an integer constant expression. 它不能是变量名,因为它必须是整数常量表达式。

Im not sure what you meant but i assume SOMEWEIRD_NAME is a Define value. 我不确定你的意思,但我认为SOMEWEIRD_NAME是一个定义值。

Define is a way to give values another name but it wont take space in you'r memorry on runtime, insted, it will be replaced everywhere the name of that defined values is writen in your code during compiling prosses. 定义是一种为值赋予另一个名称的方法,但它不会在运行时记忆中占用空间,但是,在编译前景中,在代码中写入定义值的名称时,它将被替换。

The syntax for deifne is as the following: #define NAME_OF_DEFINE 80 in the following example every NAME_OF_DEFINE in your code will be replaced whit the values 80. Notice that you shouldn't end the line whit ; deifne的语法如下所示: #define NAME_OF_DEFINE 80在以下示例中,代码中的每个NAME_OF_DEFINE都将替换为值80.请注意,您不应该结束行whit ; .

In your example i expect SOMEWEIRD_NAME to have a numbric value to set the array's size. 在您的示例中,我希望SOMEWEIRD_NAME具有numbric值来设置数组的大小。

You can fine more information about #define here 您可以在此处了解有关#define更多信息

“SOMEWEIRD_NAME”很可能是值为数字的#define,或者是枚举,其数值是它在枚举中的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM