给定这样的结构:
struct a {
int b;
int c;
my_t d[];
}
我必须传递什么来malloc
为struct a
where d
hasn
元素分配足够的内存?
struct a *var = malloc(sizeof(*var) + n*sizeof(var->d[0]))
使用变量 forsizeof
将确保在类型更改时更新大小。否则,如果您更改类型,d
或者var
如果您忘记更新任何相应的分配,则可能会因未分配足够的内存而引入静默且可能难以发现的运行时问题。
例如,您可以使用:sizeof(struct a) + sizeof(my_t [n])
.
typedef int my_t;
struct a {
int b;
int c;
my_t d[];
};
int n = 3;
main(){
printf("%zu %zu\n", sizeof(struct a), sizeof(my_t [n]));
}
结果:8 12
这应该足够了:
sizeof(a) + n * sizeof(my_t)