2
    extern struct aStruct aStruct_table[4];
    
int main()
{
        aStruct_table[0].val1 = 0;
        aStruct_table[0].val2 = 0x0;
        aStruct_table[0].val3 = 0x130;
        aStruct_table[1].val1 = 1;
        aStruct_table[1].val2 = 0x140;
        aStruct_table[1].val3 = 0x860;
        aStruct_table[1].val1 = 4;
        aStruct_table[1].val2 = 0x2050;
        aStruct_table[1].val3 = 0x1950;
        aStruct_table[1].val1 = 7;
        aStruct_table[1].val2 = 0x6000;
        aStruct_table[1].val3 = 0x666;
}

Is there another way to assign the struct array without having so much code? Maybe sth like

    extern struct aStruct aStruct_table[4] = {{0,0x0,0x130},
                                             {1,0x140,0x860},
                                             {4,0x2050,0x1950},
                                             {7,0x6000,0x666}};

2 Answers 2

4

You are mixing up assignment and initialization, I guess.

In modern C, AKA C99, the best way to do initialization of a struct is with "designated initializers"

struct aStruct A = { .val1 = 0, .val2 = 0x0A };

and the syntax for arrays of structs is just to repeat that:

struct aStruct B[] = {
   { .val1 = 0, .val2 = 0x0A },
   { .val1 = 2, .val2 = 0x0B }
};

But you shouldn't do it with the extern in front. That one is for the forward declaration in the header file without the initialization part.

If you really meant assignment, for struct you can use "compound literals

A = (struct aStruct){ .val1 = 0, .val2 = 0x0A };

but as you probably know there is no assignment syntax for arrays.

Sign up to request clarification or add additional context in comments.

3 Comments

an "assignment syntax for arrays"
You mean there is one? Try it. As I say there is initialization syntax for arrays, my variable B shows that. But there is no such thing as assignment to arrays.
OK, I mixed up between initialization and assignment, but you can initialize particular indices and skip others. Bah, nevermind.
3

Yes, it is perfectly legal to do that.

With C99 initializers it can be even clearer:

extern struct aStruct aStruct_table[4] = {
    [0] = {
        .val1 = 0,
        .val2 = 0x0,
    },
    [1] = {
// etc etc

1 Comment

@JensGustedt I forgot the dots to struct initalizers, apart from that it is perfectly valid!

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.