I have a struct defined like this:
struct StructLogDataHs {
u8_t NLogDataHsPages;
u8_t NLogDataHsChannels;
u16_t NLogDataHsSamples;
u32_t tLogDataHsTimeOffset0;
u32_t tLogDataHsTimeOffset1;
struct StructLogDataPageHs LogDataPageHs[Hs_Pages];
where the StructLogDataPageHs is defined as
struct StructLogDataPageHs {
u32_t NLogDataHsFilled;
u32_t NLogDataHsExceedingElements;
u32_t NLogDataHsExceedingData[128];
u32_t NLogDataHsPacketSize;
u32_t NLogDataHsPayloadType;
u32_t NLogDataHsAlignBytes;
u32_t NLogDataHsResevedBytes;
u32_t NLogDataHsPageHeader;
u32_t NLogDataHsTimeStamp0;
u32_t NLogDataHsTimeStamp1;
u32_t NLogDataHs[Hs_PageSize];
so it is a struct inside a struct. As you can see the size for the object NLogDataHs is defined as #define Hs_PageSize 10000 The same is done for Hs_Pages with #define Hs_Pages 3 The struct is allocated with
__attribute__ ((section(".logdata_h_slow_mem")))
struct StructLogDataHs LogDataHs;
I would like to have a second struct, with exact the same structure but with different sizes, without defining a new struct object. Is it possible to create the structure object with different sizes using the same struct definition?
CodePudding user response:
Not really.
If you wanted to dynamically allocate the structure at runtime, you could use a flexible array member at the end of StructLogDataHs
instead of a fixed length LogDataPageHs
array. But doing so would prevent you from being able to define a static instance of that structure; there is no syntax which can provide the compile-time length of an flexible array member of an individual instance.
Anyway, flexible array members cannot be nested, since the offset of an array element is computed as the product of the index and the size of the element. So all elements must have the same size. It's true that many C compilers allow variable-length arrays, but these also cannot be included in a struct
; there is nowhere to store the length of the array. [Note 1]
You could avoid typing all of those definitions twice by using macros, but you cannot have two struct StructLogDataPageHs
definitions with different values of Hs_Page_Size
; they will have to be different struct
declarations. You might be able to use an untagged struct
if you don't need to refer to the data type elsewhere in your code.
Notes:
- Multidimensional VLAs work because the compiler can allocate hidden automatic variables containing enough information to compute array offsets. But I don't know of any compiler which is prepared to add hidden
struct
members, and the C standard certainly doesn't anticipate such a feature.