Struct with union with different sized members - How can I declare the smallest struct?
-
I am writing code in standard C for a microcontroller (STM32L) and I compile with GCC. I have a struct that contains a union and the union can be of different size:
struct MyStruct
{
int someInteger;
union
{
int smallMember[1];
int bigMember[1000];
} smallOrBigMember;
};Is it possible for me to declare an object of MyStruct that only occipies 8 bytes of memory if I only intend to use the smallMember of that object?
-
I am writing code in standard C for a microcontroller (STM32L) and I compile with GCC. I have a struct that contains a union and the union can be of different size:
struct MyStruct
{
int someInteger;
union
{
int smallMember[1];
int bigMember[1000];
} smallOrBigMember;
};Is it possible for me to declare an object of MyStruct that only occipies 8 bytes of memory if I only intend to use the smallMember of that object?
No, you cannot. If you need a flexible size structure, the idiomatic solution is to add a zero size array at the end of the structure. Then, presumably, one of the fixed length fields tells you the size of the variable part. Something like this:
struct MyStruct
{
int small_or_big;
int variable_part[0]; //or int variable_part[] if you want to conform to C90
};struct MyStruct *ptr;
if (ptr->small_or_big == BIG_STRUCT)
{
ptr->variable_part[999] = some_value; //we know that variable part size is 1000
//...
}When you allocate the structure you have to account for the variable part:
//...
ptr_small = malloc(sizeof(MyStruct) + SIZE_OF_SMALL_PART);
ptr_small->big_or_small = SMALL_STRUCT;ptr_big = malloc (sizeof(MyStruct) + SIZE_OF_BIG_PART);
ptr_big->big_or_small = BIG_STRUCT;Mircea