简体   繁体   English

关于使用 int 类型的 struct hack

[英]Regarding struct hack using int type

Can we do struct hack(using int type) as below我们可以做 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);
}

Also using int type with size 1还使用大小为 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);
}

The former is the struct hack as used in c89.前者是 c89 中使用的 struct hack。 Validity of this construct has always been questionable.这种结构的有效性一直存在疑问。

The latter is a GNU struct hack, it makes use of a GNU extension and is not valid C.后者是 GNU struct hack,它使用 GNU 扩展并且不是有效的 C。

The correct way to have a structures whose size could vary at run time is to use the c99 flexible array member feature.使用 c99灵活数组成员功能来获得大小可能会在运行时变化的结构的正确方法。

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

int main(void)
{
     struct node *n = malloc(sizeof (struct node) + sizeof (int) * 10);
}

You used the same name twice.您两次使用相同的名称。 You will have to choose a different one.你将不得不选择一个不同的。 It is correct, apart from not using the correct syntax.除了没有使用正确的语法之外,它是正确的。

Should be [] not [1] or [0] , this way the code is not a "hack", but is legal from c99 onward, also called flexible array members.应该是[]而不是[1][0] ,这样代码不是“黑客”,而是从 c99 开始是合法的,也称为灵活数组成员。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM