嗯,我不明白何时以及为什么需要使用malloc来分配内存。
这是我的代码:
#include <stdlib.h>
int main(int argc, const char *argv[]) {
typedef struct {
char *name;
char *sex;
int age;
} student;
// Now I can do two things
student p;
// Or
student *ptr = (student *)malloc(sizeof(student));
return 0;
}
如果我可以直接使用student p;
,为什么需要分配内存呢?
malloc
/calloc
等函数分配内存后,请不要忘记调用free
释放内存。 - jotik