struct over array

Hi,

maybe it is a stupid question :cry: .

Can anybody tell me how to do this :

uint8_t valarr[3]={0x57,0x61,0x41};

typedef struct {
uint8_t infobyte1;
uint8_t infobyte2;
uint8_t infobyte3;
}valinfo;

valinfo *i1 = &valarr;

Serial.println(i1->infobyte1,HEX);
Serial.println(i1->infobyte2,HEX);
Serial.println(i1->infobyte3,HEX);

Error:
exit status 1
cannot convert 'uint8_t ()[3] {aka unsigned char ()[3]}' to 'valinfo*' in initialization

You could do it with a cast or with a union, but always, with code tags :wink:

Can anybody tell me how to do this :

First, you tell us WHY you want to do that.

The struct instance can be valued like an array when created. Making an array ACT like a struct doesn't seem a useful thing to do.

First, read the post by Nick Gammon at the top of this Forum for the way you should post code here. Also, it will help us if you use Ctrl-T on the source code before you post it...it's easier for us to read.

Second, as the others pointed out, this statement:

_ valinfo *i1 = &valarr;_

needs a cast: Try:

_ valinfo i1 = (valinfo) valarr;_

I have a uint_8 array with len 48 bytes that is transmitted from a machine.

It would be nice an better to read if i could address the single values by name and not by index.

Any solution for that ?

It would be nice an better to read if i could address the single values by name

Obviously, the values don't HAVE names. The variables that the values are (to be) stored in have names, at compile time. They do not have names at run time.

I don't understand the benefit of accessing unnamed data by name. Assigning names to variables that hold index values makes sense.

Thanks to econjack !

Works!

jorabo:
It would be nice an better to read if i could address the single values by name and not by index.

You could do that using enums or symbolic constants, like:

#define NAME0   valarr[0]      // Place first at the top of the file
#define NAME1   valarr[1]
#define NAME2   valarr[2]

// More code...

  Serial.println(NAME0, HEX);
  Serial.println(NAME1, HEX);
  Serial.println(NAME2, HEX);

I'm not sure what the advantage is to you of doing it. If that's all you're trying to do, is there any need for the struct?

To avoid the cast you could use a union of the struct and array. But it is essentially the same thing.