Michael P
Michael P

Reputation: 2087

C array of structs declaration

In the Linux kernel, I see a declaration of an array of structs that looks like this

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.

Upvotes: 9

Views: 473

Answers (3)

ouah
ouah

Reputation: 145899

It's a C99 designated initializer for arrays.

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. It cannot be a variable name as it has to be an integer constant expression.

Upvotes: 5

jNull
jNull

Reputation: 290

Im not sure what you meant but i assume SOMEWEIRD_NAME is a Define value.

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 ;.

In your example i expect SOMEWEIRD_NAME to have a numbric value to set the array's size.

You can fine more information about #define here

Upvotes: 2

DBug
DBug

Reputation: 2566

The "SOMEWEIRD_NAME" is most likely either a #define whose value is a number, or it's an enumeration, whose numeric value is its position in the enumeration.

Upvotes: 1

Related Questions