Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C array of structs declaration

Tags:

arrays

c

struct

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.

like image 443
Michael P Avatar asked Nov 17 '15 18:11

Michael P


People also ask

Can you store a struct in an array?

A structure may contain elements of different data types – int, char, float, double, etc. It may also contain an array as its member. Such an array is called an array within a structure. An array within a structure is a member of the structure and can be accessed just as we access other elements of the structure.

How do you create an array of structs in Objective C?

@interface Foo : NSObject { NSString *name; NSArray *books; } @end A->name = @"Clancy, Thomas"; A->books = [[NSArray alloc] initWithObjects:@"Book 1" @"Book2",nil]; self. authors = [[NSArray alloc] initWithObjects:A, nil];


3 Answers

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.

like image 101
ouah Avatar answered Oct 22 '22 17:10

ouah


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

like image 37
jNull Avatar answered Oct 22 '22 16:10

jNull


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.

like image 42
DBug Avatar answered Oct 22 '22 18:10

DBug