【发布时间】:2020-07-22 03:58:25
【问题描述】:
好吧,我不明白何时以及为什么需要使用 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;,为什么还要分配内存?
【问题讨论】:
-
阅读一本不错的 C 编程书籍。它将比我在几分钟内解释的更好更快地解释堆分配的内存。
-
你必须了解堆内存和栈内存的区别,看看这个问题:stackoverflow.com/questions/79923/…
-
别忘了在
malloc/calloc等之后致电free...
标签: c malloc dynamic-memory-allocation