0

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?

Jeegar Patel
  • 26,264
  • 51
  • 149
  • 222
Rain
  • 105
  • 1
  • 2
  • 7
  • 1
    "Doesn't work" how? I would have expected method 1 to work, but not method 2 since you can't assign arrays. For question 2, you want "some better way" but it's not clear to what you're referring. – Paul Hankin Mar 19 '21 at 07:40
  • @PaulHankin My mean is I want to store a value to uint8_t this variable, I try to use two ways to do this thing. – Rain Mar 19 '21 at 07:43
  • 1
    What Paul is saying is that you should [edit] your question and tell HOW you know it does not work. An error message for example. – klutt Mar 19 '21 at 07:50

1 Answers1

1

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

klutt
  • 30,332
  • 17
  • 55
  • 95
  • 1
    Another solution could be to make it `address[6]` (or whatever the maximum size is of the device address). Then it would still be key to use `memcpy` to assign the value. The `malloc` would not be required. – Cheatah Mar 19 '21 at 07:47
  • If I want to give a value when declaring variables, like this strcut_devInfo slave = {MACADDRESS, 0 ,5};, can i do this? – Rain Mar 19 '21 at 07:48
  • 1
    @Rain With a flexible member, no – klutt Mar 19 '21 at 07:50