【问题标题】:Regarding struct hack using int type关于使用 int 类型的 struct hack
【发布时间】:2014-02-05 23:29:21
【问题描述】:

我们可以像下面那样做 struct hack(使用 int 类型)

struct node{
   int i;
   struct node *next;
   int p[0];
}

int main(){
   struct node *n = // is this the correct hack i.e. p[10]?
      malloc(sizeof(struct node) + sizeof(int) * 10);
}

同样使用大小为 1 的 int 类型

struct node{
   int i;
   struct node *next;
   int p[1];
}

int main(){
   struct node *n = // is this a correct hack i.e. p[10]?
      malloc(sizeof(struct node) + sizeof(int) * 10);
}

【问题讨论】:

    标签: c struct


    【解决方案1】:

    前者是 c89 中使用的 struct hack。这种结构的有效性一直值得怀疑。

    后者是 GNU struct hack,它使用 GNU 扩展并且不是有效的 C。

    拥有在运行时大小可能发生变化的结构的正确方法是使用 c99 灵活的数组成员 功能。

    struct node{
        int i;
        struct node *next;
        int p[];
    }
    
    int main(void)
    {
         struct node *n = malloc(sizeof (struct node) + sizeof (int) * 10);
    }
    

    【讨论】:

      【解决方案2】:

      你两次使用了同一个名字。你将不得不选择一个不同的。 这是正确的,除了没有使用正确的语法。

      应该是[] 而不是[1][0],这样代码不是“hack”,而是从c99 开始合法,也称为灵活数组成员。

      struct node{
          int i;
          struct node *next;
          int n[];
      } ;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-19
        • 1970-01-01
        • 2017-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-01
        • 1970-01-01
        相关资源
        最近更新 更多