3

how do you initialize only one member of a structure when you create an array of if, and when you are using GCC?, for example:

#define UNUSED OxFF
typedef struct inputs{
    uint8_t state;
    uint8_t limit;
    uint8_t value;
} INPUT_TYPE;

//create array but just care that all members .state are UNUSED
INPUT_TYPE Node1[5] ={ Node1.state = UNUSED }

The initialization refers to the array bu not to the member of the struct. Of course a loop could be used, but I don't want to initialize at run-time with an "input_init" function.

jruizaranguren
  • 12,679
  • 7
  • 55
  • 73

4 Answers4

4

The syntax for initializing certain members is a C99 feature. You're close, try this one:

#define UNUSED OxFF
typedef struct inputs{
    uint8_t state;
    uint8_t limit;
    uint8_t value;
} INPUT_TYPE;

INPUT_TYPE Node1[5] = {
    {.state = UNUSED},
    {.state = UNUSED},
    {.state = UNUSED},
    {.state = UNUSED},
    {.state = UNUSED}
};

See: How to initialize a struct in accordance with C programming language standards

Edit:

As I wasn't clear enough, I edited the answer.

How array initialization work, was answered here: How to initialize all members of an array to the same value?

Community
  • 1
  • 1
Sam
  • 7,778
  • 1
  • 23
  • 49
4

I found it at last in http://gcc.gnu.org/onlinedocs/gcc-4.7.2/gcc/Designated-Inits.html#Designated-Inits its a combination of two cases.

INPUT_TYPE Node1[5] = { [0 ... 4].state = UNUSED } it is usefull in large arrays.

2

Since UNUSED is a non-zero value, you'll need to specify the initializer for each element of the array if that's what you need:

INPUT_TYPE Node1[5] = { 
    {.state = UNUSED}, 
    {.state = UNUSED}, 
    {.state = UNUSED}, 
    {.state = UNUSED}, 
    {.state = UNUSED}
};
Michael Burr
  • 333,147
  • 50
  • 533
  • 760
0

Why not use a constructor for init:

#define UNUSED OxFF
typedef struct inputs{
    uint8_t state;
    uint8_t limit;
    uint8_t value;

   inputs(){state = UNUSED, limit, value;};

} INPUT_TYPE;

?

Leo Chapiro
  • 13,678
  • 8
  • 61
  • 92