我最近有一项任务,我必须动态地为结构分配内存。我用这个方法:
myStruct *struct1 = malloc(sizeof *struct1);
这很好用。但是,我不明白怎么做。我认为struct1
指针在那时未初始化,因此应该没有任何大小。那么malloc(sizeof *struct1)
如何返回有效的内存量来分配?
答案 0 :(得分:5)
sizeof
运算符不会计算操作数。它只是看着类型。例如:
#include <stdio.h>
int main(void)
{
int i = 0;
printf("%zu\n", sizeof i++);
printf("%d\n", i);
return 0;
}
如果您运行上述程序,您会看到i
仍为0。
因此,在您的示例中,*struct1
未被评估,它仅用于类型信息。
答案 1 :(得分:0)
malloc(sizeof(*struct1))
分配的内存量等于结构的大小,具体取决于您声明的结构变量的数量。 Sizeof用于返回struct1的大小,该大小在编译期间找到。
答案 2 :(得分:0)
试试吧。首先声明结构,
typedef struct {
int a;
int b;
int c;
}MyStruct;
然后在分配内存之前,初始化一个结构变量并按给定的内容分配内存,
MyStruct test;
printf("~~~~~ sizeofStruct: %ld", sizeof(test));
MyStruct *myAlloc = (MyStruct *)malloc(sizeof(test));
printf("~~~~~ sizeofmyAlloc: %ld", sizeof(*myAlloc));
干杯!