gpt4 book ai didi

c - 关于使用 int 类型的 struct hack

转载 作者:行者123 更新时间:2023-12-02 04:37:42 26 4
gpt4 key购买 nike

我们可以像下面那样做 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);
}

最佳答案

前者是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);
}

关于c - 关于使用 int 类型的 struct hack,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21590892/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com