struct stu { char name[20]; long num; struct data birthday; };
struct stu *p1, *p2;
p1 = malloc(sizeof(struct stu)); // 必須分配空間
p1->name; p1->num; p1->birthday.year; // 箭頭運算符訪問成員
malloc 從堆分配空間,sizeof 計算類型大小。釋放用 free(p1)。
定義 struct stu student[4], *p;,令 p = student;,p 指向數組首元素。三種訪問方式:
(p+i)->member 或 (student+i)->member,等價 &student[i]。p++ 移向下一元素,用 p->member 訪問。p[i].member,效果同 student[i].member。struct data { int day, month, year; };
struct stu { char name[20]; long num; struct data birthday; };
main() {
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);
}
輸出四行學生姓名、學號、出生年月日。