0

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 ?

2 Answers 2

2

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},
    },
};
Sign up to request clarification or add additional context in comments.

4 Comments

@anastaciu Oh, OP said "The following example works well." but it actually won't...
Yes, recurrent problem :)
@MikeCAT Code fixed, never heard about compound literals before. Thanks
@Arkaik, well, only one thing left to do, UV and accept.
0

value is not an array, but a pointer. You must initialize it by referring to the array that exists elsewhere.

Indeed name works differently because the lexical literal syntax for strings "like this" create an unnamed array of chars.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.