6

I have a struct:

struct TypeValue{
 u8 type;
 union{
   u8 u8value;
   s8 s8value;
 }value;
}

Depending on type var we can have value from u8value or s8value. Now I have a struct TypeValue and I want to get the void pointer to the value element (dont care pointer type), which one is correct:

void *ptr = &typevalue.value (1)
OR
void *ptr = &typevalue.value.u8value (2)

(put this in a for loop to find correct value depending on type)

Of course (2) is a correct way but I have to loop through the data type to get the correct pointer to correct value. But question is if (1) is correct as I am wondering if the pointer to the union is equal to the pointer to its element? Does big/little endian affect the result?

Maluvel
  • 425
  • 1
  • 6
  • 13

2 Answers2

5

void *ptr = &typevalue.value will do, because C standard (N1570, 6.7.2.1 Structure and union specifiers) says:

16 The size of a union is sufficient to contain the largest of its members. The value of at most one of the members can be stored in a union object at any time. A pointer to a union object, suitably converted, points to each of its members (or if a member is a bit- field, then to the unit in which it resides), and vice versa.

Address only makes sense in the current running environment (you don't store the address to flash), so endianness of address doesn't matter.

user694733
  • 15,208
  • 2
  • 42
  • 68
4

The three ideas are correct.

void *ptr = &(typevalue.value.u8value);
void *ptr = &(typevalue.value.s8value);
void *ptr = &(typevalue.value);

A union is a struct on memory that take the size of the larger type declared inside. All the fields use the same memory space, is just giving semantical information to the definition.

chfumero
  • 1,137
  • 2
  • 13
  • 26