C 中单个结构成员的大小 [英] sizeof single struct member in C
问题描述
我试图声明一个依赖于另一个结构的结构.我想使用 sizeof
来保证安全/迂腐.
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 ;
现在我想声明一个与 parent_t.text
大小相同的结构 child_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 ;
我用 parent_t
和 struct _parent
尝试了几种不同的方法,但我的编译器不接受.
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 ;
是否可以在不使用dummy
的情况下声明child_t
?
Is it possible to declare child_t
without the use of dummy
?
推荐答案
虽然使用 #define
定义缓冲区大小是一种惯用的方法,但另一种方法是使用这样的宏:
Although defining the buffer size with a #define
is one idiomatic way to do it, another would be to use a macro like this:
#define member_size(type, member) sizeof(((type *)0)->member)
并像这样使用它:
typedef struct
{
float calc;
char text[255];
int used;
} Parent;
typedef struct
{
char flag;
char text[member_size(Parent, text)];
int used;
} Child;
我实际上有点惊讶 sizeof((type *)0)->member)
甚至允许作为常量表达式.很酷的东西.
I'm actually a bit surprised that sizeof((type *)0)->member)
is even allowed as a constant expression. Cool stuff.
这篇关于C 中单个结构成员的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!