Search code examples
carduinoflexible-array-member

How to initialize structure having unint_t as flexible array member?


I define a struct, have a one-member the type is uint8_t, this member store mac address.

Programming on Arduino IDE.

Struct:

typedef struct devInfo{
  uint8_t address[];
  unsigned int count;
  unsigned int filePos;
}struct_devInfo;
  • Quesion 1:

I use these two ways to give a value but cannot assign value to variable.

Method 1 > struct_devInfo slave = {{0xA1, 0xB2, 0xC3, 0xD4, 0xE5, 0xF6}, 0, 0};

Method 2 > slave.address[] = {0xA1, 0xB2, 0xC3, 0xD4, 0xE5, 0xF6};

How can I access this type of value?

  • Question 2:

I will use the variables of this structure, salve1, slave2... etc.

In addition to the structure, is there some better way? Can you demonstrate?


Solution

  • A struct with a flexible array member needs to be the last member in the struct. Change to

    typedef struct devInfo{
      unsigned int count;
      unsigned int filePos;
      uint8_t address[];
    }struct_devInfo;
    

    Then you need to allocate enough memory:

    struct_devInfo *p = malloc(sizeof *p + size);
    

    Then you could do this:

    const uint8_t initArr[] = {0xA1, 0xB2, 0xC3, 0xD4, 0xE5, 0xF6};
    memcpy(p, initArr, sizeof initArr);
    

    But since it seems to be a field that does not require a flexible member, I'd use this instead:

    typedef struct devInfo{
      unsigned int count;
      unsigned int filePos;
      uint8_t address[6]; // Specify the size
    }struct_devInfo;
    

    Then you don't need to allocate memory