关于使用int类型的结构hack
我们可以像下面那样进行结构破解(使用int类型)吗 也使用大小为1的int类型关于使用int类型的结构hack,c,struct,C,Struct,我们可以像下面那样进行结构破解(使用int类型)吗 也使用大小为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); } 前者是c89中使用的struct hack。
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);
}
前者是c89中使用的struct hack。这一构想的有效性一直受到质疑 后者是GNU结构黑客,它使用GNU扩展,并且不是有效的C 使结构在运行时大小可能不同的正确方法是使用c99灵活阵列成员功能
你用了两次相同的名字。你必须选择一个不同的。 除了没有使用正确的语法之外,它是正确的 应该是
[]
而不是[1]
或[0]
,这样代码就不是“黑客”,而是从c99开始合法的,也称为灵活数组成员
struct node{
int i;
struct node *next;
int n[];
} ;
struct node{
int i;
struct node *next;
int p[];
}
int main(void)
{
struct node *n = malloc(sizeof (struct node) + sizeof (int) * 10);
}
struct node{
int i;
struct node *next;
int n[];
} ;