malloc和free都包含在<stdlib.h>頭文件中
局部變量由於存儲在棧中,一旦離開函數,變量就會被釋放,當我們需要將數據持久使用,就需要將數據保存到堆中,而在堆中申請內存空間就需要malloc方法;malloc方法在堆中建立一片內存空間,然後返回一個指針,這個指針是void*類型,保存了這片內存的其實地址
folder* f=malloc(sizeof(folder));//通過sizeof告訴系統folder數據類型在系統中占用的空間大小
free是和malloc配對使用的,一旦malloc創建的空間不需要了就需通過free釋放,如果不這樣做很容易造成內存洩漏;將指針傳遞給free函數就行
free(f);
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 typedef struct folder{
5 int level;
6 char* filename;
7 struct folder* child;
8 }folder;
9
10 int main(){
11 folder* f=malloc(sizeof(folder));//通過sizeof告訴系統folder數據類型在系統中占用的空間大小
12 f->level=1;
13 f->filename="first";
14 f->child=NULL;
15 printf("%s level is %i",f->filename,f->level);
16 free(f);
17 return 0;
18 }