Search code examples
arrayscpointersstructurestatic-initialization

Static initialization of int array from within structure initialization


I'm trying to statically declare and initialize a structure array containing both char and int arrays.

The following example works well.

typedef struct myStruct
{
    char* name;
    uint8_t size;
    uint8_t *value;
}myStruct;

uint8_t struct1_value[] = {0x00, 0x01};
uint8_t struct2_value[] = {0x00, 0x01, 0x03, 0x04};

myStruct myStructArray[] = {
    [0] = {
        .name = "Struct_1",
        .size = 2,
        .value = struct1_value,
    },
    [1] = {
        .name = "Struct_2",
        .size = 4,
        .value = struct2_value,
    },
};

I can't find a syntax that allows to initialize value field directly from myStructArray

I would like to know if there is a way to initialize the value field without having to declare struct1_value and struct2_value variables.

Maybe it's just not possible in pure C but as it's possible to statically initialize a char array, why not with a int array ?


Solution

  • You can use compound literals.

    myStruct myStructArray[] = {
        [0] = {
            .name = "Struct_1",
            .size = 2,
            .value = (uint8_t[]){0x00, 0x01},
        },
        [1] = {
            .name = "Struct_2",
            .size = 4,
            .value = (uint8_t[]){0x00, 0x01, 0x03, 0x04},
        },
    };