问题描述
我最近有一个作业,必须为结构动态分配内存.我使用了这种方法:
I recently had an assignment where I had to dynamically allocate memory for a struct. I used this method:
myStruct *struct1 = malloc(sizeof *struct1);
这很好.但是,我不知道如何.我认为 struct1
指针当时尚未初始化,因此应该没有任何大小.因此, malloc(sizeof * struct1)
如何返回有效的内存量进行分配?
This worked just fine. However, I don't understand how. I would think that the struct1
pointer is uninitialized at that point and should therefore have a size of nothing. So therefore how does malloc(sizeof *struct1)
return a valid amount of memory to allocate?
推荐答案
sizeof
运算符不评估操作数.它只是看类型.例如:
sizeof
operator in C doesn't evaluate the operand. It just looks at the type. For example:
#include <stdio.h>
int main(void)
{
int i = 0;
printf("%zu\n", sizeof i++);
printf("%d\n", i);
return 0;
}
如果运行上述程序,则会看到 i
仍为0.
If you run the above program, you will see that i
is still 0.
因此,在您的示例中,未评估 * struct1
,它仅用于类型信息.
So, in your example, *struct1
is not evaluated, it's only used for type information.
这篇关于如何在C中动态分配结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!