前言:為了能夠動態配製記憶體,利用 malloc()來跟記憶體申請空間(HEAP),HEAP空間不像STACK空間會自己釋放掉,所以必須依靠free() 來釋放記憶體。
code sample:
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // 為了使用strdup
typedef struct island//<-命名 island 資料結構為linklist
{
char *name;
char *open;
char *close;
struct island *next ; //遞回結構不能取消"命名"
}island;//<-別名
island* creat(char* name)
{
island *i = malloc(sizeof(island));
i->name = strdup(name); //請憶體配置name複本空間
i->open = "09:00";
i->close = "17:00";
i->next = NULL;
return i;
}
void display(island *start)
{
island *i = start;
for(;i!=NULL;i=i->next)
{
printf("name:%s open:%s - %s\n", i->name,i->open,i->close);
}
}
void release(island *start)
{
island *i = start;
island *next = NULL;
for(;i!=NULL;i=next)
{
next = i->next;
free(i->name);
free(i);
}
}
int main(int argc, char *argv[])
{
island *start = NULL;
island *i = NULL;
island *next = NULL;
char name[80];
int count =0;
for(;scanf("%79[^,],[\n]\n",name)== 1;i = next)
{
next =creat(name);
if(start == NULL)
start = next;
if(i != NULL)
i->next = next;
}
display(start);
release(start);
return 0;
}
沒有留言:
張貼留言