//建立一個有三名學生數據的單向動態鏈表#include<stdio.h>#include<malloc.h>#define NULL 0#define LEN sizeof(struct student)struct student{ long num; float score; struct student *next;};int n;struct student *creat(void)/*定義函數。此函數帶回一個指向鏈表頭的指針*/{ struct student *head; struct student *p1,*p2; n=0; p1=p2=(struct student *)malloc(LEN);/*開辟一個新單元*/ scanf("%ld,%f",&p1->num,&p1->score); head=NULL; while(p1->num!=0) { n=n+1; if(n==1) head=p1; else p2->next=p1; p2=p1; p1=( struct student * )malloc(LEN); scanf("%ld,%f",&p1->num,&p1->score); } p2->next=NULL; return(head);}//為什么可以直接寫( struct student * ),還有malloc這個函數大神能為我舉個例子說明一下嗎
2 回答
已采納

瓦特賣輪鴨
TA貢獻1條經驗 獲得超0個贊
你指的是malloc前面括號里的struct student *吧,這個代表你要使用malloc函數為賦值符左邊的指針分配剛剛好儲存一個結點的內存。據我了解到的,malloc.h這個頭文件跟stdlib.h頭文件都包含malloc函數作為動態分配內存函數,用法一般是 指針名=(數據類型*)malloc(n*sizeof(數據類型)),這里的sizeof(數據類型)是此數據類型的單元內存,所以n就代表你要申請n個這種數據類型的單元內存。為了書寫方便簡潔,一般用typedef給結點命一個特殊好記有意義的名兒,比如typedef struct {xxx;}student;然后直接用student作為結點類型命名變量。
- 2 回答
- 0 關注
- 2651 瀏覽
添加回答
舉報
0/150
提交
取消