Makogan
Makogan

Reputation: 9540

Is it possible to define a size changing structure in c?

If you were to declare something like:

struct MyStruct
{
   int field1;
   int[] field2;
   int field3;
}

field 2 is actually a pointer to an array, rather than being the array itself. So MyStruct retains a size of 3 bytes. I wonder if there is a way to do something similar, except that field2 should be the array itself and not a pointer.

Obviously you could do this with just an array, but my final goal is to be able to have different types of varying size in the aforementioned structure; which would require padding (which I do not want).

Is this possible at all?

Upvotes: 1

Views: 175

Answers (1)

Hiko Haieto
Hiko Haieto

Reputation: 433

The union will be at least as large as the largest item in the union, no smaller. If you are currently using one of the smaller items, it will not shrink the size of the union or the outer struct it is part of. However, the items before and after the union will still be safe and physically present before and after the memory used for the union, even if the memory currently being used by them do not exactly touch. This question shows an example of precisely how you can create such a union.

In response to the update, if the outer struct truly must be the same size regardless of the union, then the best you could hope to do is have a pointer to the union contents instead of the union itself. The union would still not be the "minimum" size though. Otherwise, do as dbush suggests and have three outer structs, with no use of union at all.

Upvotes: 1

Related Questions