struct data { int day, month, year; };
struct stu { char name[20]; long num; struct data birthday; };
main() {
struct stu *student = malloc(sizeof(struct stu));
scanf("%s", student->name);
scanf("%ld", &student->num);
scanf("%d%d%d", &student->birthday.year,
&student->birthday.month, &student->birthday.day);
printf("%20s%10ld%10d//%d//%d\n",
student->name, student->num,
student->birthday.year, student->birthday.month, student->birthday.day);
}
malloc 分配堆空間,sizeof 確保大小正確。student->birthday.year 逐級訪問。-> 等價於 (*student).member。定義 struct stu student[4], *p; p = student;
(student+i)->member、(p+i)->member,等價 &student[i]。p++ 移向下一元素,p->member 訪問。p[i].member,效果同 student[i].member。struct stu *p, student[4] = {
{"liying",1,{1978,5,23}}, {"wangping",2,{1979,3,14}},
{"libo",3,{1980,5,6}}, {"xuyan",4,{1980,4,21}}
};
p = student;
for (int i=0;i<4;i++)
printf("%20s%10ld%10d//%d//%d\n",
(p+i)->name, (p+i)->num,
(p+i)->birthday.year, (p+i)->birthday.month, (p+i)->birthday.day);
採用地址法 (p+i)-> 輸出四學生完整資料。