应该怎么写这个#define

[复制链接]
1398|6
 楼主| 大道至简 发表于 2014-7-16 08:38 | 显示全部楼层 |阅读模式
#define DataBoad_Max_lenth 64
union DataBody
{
struct a aa;
struct b bb;
struct c cc;
unsigned char cells[DataBoad_Max_lenth]; //上面所有的结构都不能超过64字节
};


假设

sa=sizeof(struct a);

sb=sizeof(struct b);

sc=sizeof(struct c);

我想把#define DataBoad_Max_lenth更改成sa、sb、sc之中最大的那个数,应该怎么写这个#define
原野之狼 发表于 2014-7-16 09:01 | 显示全部楼层
照这个思路,无解。

sa=sizeof(struct a)是在编译的时候求解,因此预编译的时候不知道sa是多少。
shell.albert 发表于 2014-7-16 09:17 | 显示全部楼层
可以使用一个指针,
在32位机器下,void*占用4个字节,在64位下占用8个字节。
在编译的时候,动态申请内存,使用类似malloc()或new之类的,
lxyppc 发表于 2014-7-16 09:24 来自手机 | 显示全部楼层
楼主思路进死胡同了,想想union的本质

#define DataBoad_Max_lenth 1
dragon_hn 发表于 2014-7-16 09:38 | 显示全部楼层

struct a
{
        char test[12];
};

struct b
{
        char test[14];
};

struct c
{
        char test[15];
};

union DataBody_1
{
        struct a aa;
        struct b bb;
        struct c cc;
};

#define                DataBoad_Max_lenth        sizeof(DataBody_1)

union DataBody
{
        struct a aa;
        struct b bb;
        struct c cc;
        unsigned char cells[DataBoad_Max_lenth]; //ÉÏÃæËùÓеĽṹ¶¼²»Äܳ¬¹ý64×Ö½Ú
};
原野之狼 发表于 2014-7-16 12:43 | 显示全部楼层
dragon_hn 发表于 2014-7-16 09:38
struct a
{
        char test[12];

这个可行,规避了预编译期间求MAX的操作。
原野之狼 发表于 2014-7-16 12:54 | 显示全部楼层
  1. /* not tested... */
  2. typedef struct _foo {
  3.     unsigned char addr[0];
  4.     union {
  5.         struct _bar1 bar1;
  6.         struct _bar2 bar2;
  7.         struct _bar3 bar3;
  8.     } bar;
  9.     #define BAR_SIZE sizeof(bar)   /* used for overflow check */
  10. } Foo;
您需要登录后才可以回帖 登录 | 注册

本版积分规则

个人签名:看大道至简所著的《感悟设计》,感悟设计的至简大道

7563

主题

9527

帖子

18

粉丝
快速回复 在线客服 返回列表 返回顶部