In my application I have a number of different structure variables. In all cases the members are unsigned char. I pass the structure to a function via a pointer where the various structures may have a different number of members with different names. Within the function I need to access the members in an indexed form. It is easy enough to use the first member to contain the size of the structure. If I used an array, indexing would be simple, but this would create problems down the line. Arrays aso have their problems - for example, strlen() returns a value of 0XFF if the array is uninitialised, as would be the case for an array that is to be written. I suppose I could always use an array to pass the data to/from the function and transfer between array and structure in the calling function, but that is hardly elegant programming!!!!
A union is useful if you want one variable (a union type) to be able to hold different types of data at different times.
A union is also helpful for accessing the same data in different ways (e.g. as named members of a structure, and as elements of an array). Be aware that this is machine-specific and code that relies on using a union this way needs to be modified accordingly when compiled on a different architecture.
E.g.
typedef struct { unsigned char length; unsigned char some_data; unsigned char more_data; unsigned char yet_more_data; } my_data_struct; typedef union { my_data_struct as_struct; unsigned char as_array; } my_data_union; ... { my_data_union my_data; ... my_data.as_struct.length = 3; my_data.as_struct.some_data = 0xAB; my_data.as_struct.more_data = 0xDE; my_data.as_struct.yet_more_data = 0xF0; ... peripheral_outpt = my_data.as_array[0]; wait_for_peripheral(); peripheral_outpt = my_data.as_array[1]; wait_for_peripheral(); peripheral_outpt = my_data.as_array[2]; wait_for_peripheral(); peripheral_outpt = my_data.as_array[3]; ... }
Thanks for that, I think I have been given enough ideas to keep me busy for some time.
typedef union { my_data_struct as_struct; unsigned char as_array; } my_data_union;
should be
typedef union { my_data_struct as_struct; unsigned char as_array[4]; } my_data_union;