C:单一的sizeof结构成员 [英] C: sizeof single struct member

查看:145
本文介绍了C:单一的sizeof结构成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想声明一个结构是依赖于另一结构。
我想用的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 ;

现在我要声明一个struct child_t 具有尺寸 parent_t.text 相同。

Now I want to declare a struct child_t that has the same size as parent_t.text.

我怎样才能做到这一点? (伪code以下。)

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 结构_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 ;

是否有可能申报 child_t 而不使用的虚拟

感谢。

推荐答案

虽然定义一个与的#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((键入*)0) - >成员)甚至允许作为常量前pression。很酷的东西。

I'm actually a bit surprised that sizeof((type *)0)->member) is even allowed as a constant expression. Cool stuff.

这篇关于C:单一的sizeof结构成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆