# include <stdio.h> # include <string.h> struct AGE { int year; int month; int day; }; struct STUDENT { char name[20]; //姓名 int num; //學號 struct AGE birthday; //生日 float score; //分數 }; int main(void) { struct STUDENT student1; /*用struct STUDENT結構體型別定義結構體變數student1*/ struct STUDENT *p = NULL; /*定義一個指向struct STUDENT結構體型別的指標變數p*/ p = &student1; /*p指向結構體變數student1的首地址, 即第一個成員的地址*/ strcpy((*p).name, "小明"); //(*p).name等價於student1.name (*p).birthday.year = 1989; (*p).birthday.month = 3; (*p).birthday.day = 29; (*p).num = 1207041; (*p).score = 100; printf("name : %sn", (*p).name); //(*p).name不能寫成p printf("birthday : %d-%d-%dn", (*p).birthday.year, (*p).birthday.month, (*p).birthday.day); printf("num : %dn", (*p).num); printf("score : %.1fn", (*p).score); return 0; }輸出結果是:
(*指標變數名).成員名
注意,*p 兩邊的括號不可省略,因為成員運算子“.”的優先順序高於指標運算子“*”,所以如果 *p 兩邊的括號省略的話,那麼 *p.num 就等價於 *(p.num) 了。(*指標變數名).成員名
可以直接用:指標變數名->成員名
來代替,它們是等價的。“->”是“指向結構體成員運算子”,它的優先順序同結構體成員運算子“.”一樣高。p->num 的含義是:指標變數 p 所指向的結構體變數中的 num 成員。p->num 最終代表的就是 num 這個成員中的內容。# include <stdio.h> # include <string.h> struct AGE { int year; int month; int day; }; struct STUDENT { char name[20]; //姓名 int num; //學號 struct AGE birthday; /*用struct AGE結構體型別定義結構體變數birthday, 生日*/ float score; //分數 }; int main(void) { struct STUDENT student1; /*用struct STUDENT結構體型別定義結構體變數student1*/ struct STUDENT *p = NULL; /*定義struct STUDENT結構體型別的指標變數p*/ p = &student1; /*p指向結構體變數student1的首地址, 即第一項的地址*/ strcpy(p->name, "小明"); p->birthday.year = 1989; p->birthday.month = 3; p->birthday.day = 29; p->num = 1207041; p->score = 100; printf("name : %sn", p->name); //p->name不能寫成p printf("birthday : %d-%d-%dn", p->birthday.year, p->birthday.month, p->birthday.day); printf("num : %dn", p->num); printf("score : %.1fn", p->score); return 0; }輸出結果是:
# include <stdio.h> struct STU { char name[20]; int age; char sex; char num[20]; }; int main(void) { struct STU stu[5] = {{"小紅", 22, 'F', "Z1207031"}, {"小明", 21, 'M', "Z1207035"}, {"小七", 23, 'F', "Z1207022"}}; struct STU *p = stu; return 0; }此時指標變數 p 就指向了結構體陣列的第一個元素,即指向 stu[0]。我們知道,當一個指標指向一個陣列後,指標就可以通過移動的方式指向陣列的其他元素。
# include <stdio.h> struct STU { char name[20]; int age; char sex; char num[20]; }; int main(void) { struct STU stu[3] = {{"小紅", 22, 'F', "Z1207031"}, {"小明", 21, 'M', "Z1207035"}, {"小七", 23, 'F', "Z1207022"}}; struct STU *p = stu; for (; p<stu+3; ++p) { printf("name:%s; age:%d; sex:%c; num:%sn", p->name, p->age, p->sex, p->num); } return 0; }輸出結果是:
# include <stdio.h> struct STU { char name[20]; int age; char sex; char num[20]; }; int main(void) { struct STU stu[3] = {{"小紅", 22, 'F', "Z1207031"}, {"小明", 21, 'M', "Z1207035"}, {"小七", 23, 'F', "Z1207022"}}; struct STU *p = stu; int i = 0; for (; i<3; ++i) { printf("name:%s; age:%d; sex:%c; num:%sn", p[i].name, p[i].age, p[i].sex, p[i].num); } return 0; }輸出結果是: