Search code examples
arrayscstructure

How to make variables same for all structures in array of structures


I am trying to make 2 variables of structure same across whole array of structures. I am wondering how would you do that as I cant find any clue about what I want to do. I am using C language Here is the structure definition.

struct exp
    {
    uint8_t ReadA[2];
    uint8_t ReadB[2];
    GPIO_TypeDef* port;
    uint16_t pinmask;
    uint8_t Arec[1];
    uint8_t Brec[1];
    } exps[2];
}

I have tried several options.

exps.ReadA={0x41,0x12};
exps[].ReadA[]={0x41,0x12};
exps[].ReadA={0x41,0x12};
exps.ReadA[]={0x41,0x12};
exps->ReadA={0x41,0x12};
exps[]->ReadA[]={0x41,0x12};
exps[]->ReadA[]={0x41,0x12};
exps[]->ReadA[]={0x41,0x12};

None of them work and they give me errors that something is expected before token (],{,;) Only work around I have found to work is to go to write the data snippet by snippet. This is what I mean:

exps[0].ReadA[0]=0x41;
exps[0].ReadA[1]=0x12;

exps[0].ReadB[0]=0x41;
exps[0].ReadB[1]=0x13;

exps[1].ReadB[0]=0x41;
exps[1].ReadB[1]=0x12;

exps[1].ReadB[0]=0x41;
exps[1].ReadB[1]=0x13;

Also I need to make that array of structure bigger (15 to 20 structures)


Solution

  • OP has revealed, after being asked, that they are searching for a "compile-time" solution.

    This stripped down code should point the way.

    #include <stdio.h>
    
    int main( void ) {
    
        struct exp {
    
            uint8_t A[2];
            uint8_t B[2];
            /* additional struct members are initialised to 0 or NULL */
    
            } e[ 3 ] = { // NB: 3 specified
    
                { { 0x41, 0x12 }, { 0x41, 0x13 } }, // <== e[0]
                { { 0x41, 0x12 }, { 0x41, 0x13 } }, // <== e[1]
                /* e[2] initial values default to 0 */
    
            };
    
        printf( "e[0] vals: %02X %02X %02X %02X\n", e[0].A[0], e[0].A[1], e[0].B[0], e[0].B[1] );
        printf( "e[1] vals: %02X %02X %02X %02X\n", e[1].A[0], e[1].A[1], e[1].B[0], e[1].B[1] );
        printf( "e[2] vals: %02X %02X %02X %02X\n", e[2].A[0], e[2].A[1], e[2].B[0], e[2].B[1] );
    
        return 0;
    }
    

    Output:

    e[0] vals: 41 12 41 13
    e[1] vals: 41 12 41 13
    e[2] vals: 00 00 00 00
    

    Provide an appropriate value (with appropriate syntax) for every array element and/or struct member to be initialised. Values not provided will be set to 0 (or NULL) by the compiler. There is no appropriate "duplicate these values 'x' times" syntax. (Please don't write nested macros that try to achieve this. Stay away from the forces of darkness.)