Search code examples
cstructarmiar

How to init a structure array in C?


I'm coding on a development board with an ARM processor, so I use IAR WORKBENCH as IDE. I wonder why compiler gives me an error when training to manually initialize an array of structures, code is below: Struct definition:

typedef void (*Function)(void);

typedef struct _Task
{
    uint8_t priority;
    Function *func;
    uint8_t exec_state;
}Task; 

Attempt to initialize an array of structure:

Task* task_array_test[3] = {
        HIGH , &Switch_LED_RED , IDLE,
        MED , &Switch_LED_RED , IDLE,
        LOW , &Reset_LED      , IDLE
};

IDLE, LOW, MED, HIGH - are macros with unsigned int values.

Compiler errors:

Error[Pe144]: a value of type "unsigned int" cannot be used to initialize an entity of type "Task *" 
Error[Pe144]: a value of type "void (*)(void)" cannot be used to initialize an entity of type "Task *" 
Error[Pe146]: too many initializer values 

Any help is welcome!


Solution

  • First what was already mentioned by @pmg - an array of type Task would do, probably no need for an array of pointers Task*

    In addition you don't need func to be of type Function* as well:

    typedef void (*Function)(void);
    
    typedef struct _Task
    {
        uint8_t priority;
        Function func;
        uint8_t exec_state;
    }Task; 
    

    Your array initialization would then look like this:

    Task task_array_test[] = {
            HIGH , Switch_LED_RED , IDLE,
            MED ,  Switch_LED_RED , IDLE,
            LOW ,  Reset_LED      , IDLE
    };
    

    But I prefer to put every element in braces as well for better reading:

     Task task_array_test[] = {
                { HIGH , Switch_LED_RED , IDLE },
                { MED ,  Switch_LED_RED , IDLE },
                { LOW ,  Reset_LED      , IDLE }
        };