I am trying to declare a struct that is dependent upon another struct.
I want to use sizeof
to be safe/pedantic.
typedef struct _parent
{
float calc ;
char text[255] ;
int used ;
} parent_t ;
Now I want to declare a struct child_t
that has the same size as parent_t.text
.
How can I do this? (Pseudo-code below.)
typedef struct _child
{
char flag ;
char text[sizeof(parent_t.text)] ;
int used ;
} child_t ;
I tried a few different ways with parent_t
and struct _parent
, but my compiler will not accept.
As a trick, this seems to work:
parent_t* dummy ;
typedef struct _child
{
char flag ;
char text[sizeof(dummy->text)] ;
int used ;
} child_t ;
Is it possible to declare child_t
without the use of dummy
?
Although defining the buffer size with a
#define
is one idiomatic way to do it, another would be to use a macro like this:and use it like this:
I'm actually a bit surprised that
sizeof((type *)0)->member)
is even allowed as a constant expression. Cool stuff.I am not on my development machine right now, but I think you can do one of the following:
Edit: I like the member_size macro Joey suggested using this technique, I think I would use that.
@joey-adams, thank you! I was searching the same thing, but for non char array and it works perfectly fine even this way:
It returns 20 as expected.
And, @brandon-horsley, this works good too:
Use a preprocessor directive, i.e. #define:
Another possibility would be to define a type. The fact that you want to ensure the same size for the two fields is an indicator that you have the same semantics for them, I think.
and then have a field
in both of your types.
You are free to use
FIELD_SIZEOF(t, f)
in the Linux kernel. It's just defined as following:This type of macro is mentioned in other answers. But it's more portable to use an already-defined macro.