结构分配问题
这3个有什么区别?基本一样吗?
struct X* x = (struct X*)malloc(sizeof(struct X));
struct X* x = (struct X*)malloc(sizeof(x));
struct X* x = (struct X*)malloc(sizeof *x);
回答
他们是不一样的:
sizeof(struct X)使用struct X定义分配空间。sizeof(x)根据 的大小分配空间x。x是一个指针来struct X,和指针很可能会根据您的系统上4首或8个字节。sizeof *x根据 的大小分配空间*x,其类型是 的对象struct X。因此,这分配了与 1.^ 相同的空间量
2 不正确。分配内存时,您希望为“上一级”分配空间。在这种情况下,x是一种struct X*类型,因此您必须为struct X对象分配足够的空间。1 和 3 都这样做。其中,3 种通常被认为是首选做法,因为它需要较少的维护。稍后考虑,您决定在这里使用新结构,struct myNewStruct* x. 对于 1,您还必须将请求的内存量更改为malloc(sizeof(myNewStruct)). 如果使用 3,则无需额外工作,因为 now*x是一种struct myNewStruct类型,可以malloc“自动”提供正确的尺寸。另请注意,出于类似的原因,将 的返回结果转换malloc为不好的做法,因为您还需要将转换从 更改(struct X*)为(struct myNewStruct*)。
// This will compile and work, but see how many things have to change
// if your struct type ever changes? Three changes are required
struct myNewStruct* x = (struct myNewStruct*)malloc(sizeof(struct myNewStruct));
// as opposed to this, where only one change is needed
struct myNewStruct* x = malloc(sizeof *x);
^重要的是要注意sizeof几乎总是在编译时评估(我认为唯一的例外是 VLA),并且操作数类型的大小是被评估的。