struct stu{
char *name; //姓名
int num; //學號
int age; //年齡
char group; //所在小組
float score; //成績
} stu1 = { "Tom", 12, 18, 'A', 136.5 };
//結構體指針
struct stu *pstu = &stu1;
也可以在定義結構體的同時定義結構體指針:
struct stu{
char *name; //姓名
int num; //學號
int age; //年齡
char group; //所在小組
float score; //成績
} stu1 = { "Tom", 12, 18, 'A', 136.5 }, *pstu = &stu1;
注意,結構體變量名和數組名不同,數組名在表達式中會被轉換為數組指針,而結構體變量名不會,無論在任何表達式中它表示的都是整個集合本身,要想取得結構體變量的地址,必須在前面加&,所以給 pstu 賦值只能寫作:
struct stu *pstu = &stu1;
而不能寫作:struct stu *pstu = stu1;
還應該注意,結構體和結構體變量是兩個不同的概念:結構體是一種數據類型,是一種創建變量的模板,編譯器不會為它分配內存空間,就像 int、float、char 這些關鍵字本身不占用內存一樣;結構體變量才包含實實在在的數據,才需要內存來存儲。下面的寫法是錯誤的,不可能去取一個結構體名的地址,也不能將它賦值給其他變量:
struct stu *pstu = &stu;
struct stu *pstu = stu;
.的優先級高於*,(*pointer)兩邊的括號不能少。如果去掉括號寫作*pointer.memberName,那麼就等效於*(pointer.numberName),這樣意義就完全不對了。->是一個新的運算符,習慣稱它為“箭頭”,有了它,可以通過結構體指針直接取得結構體成員;這也是->在C語言中的唯一用途。
#include <stdio.h>
int main(){
struct{
char *name; //姓名
int num; //學號
int age; //年齡
char group; //所在小組
float score; //成績
} stu1 = { "Tom", 12, 18, 'A', 136.5 }, *pstu = &stu1;
//讀取結構體成員的值
printf("%s的學號是%d,年齡是%d,在%c組,今年的成績是%.1f!\n", (*pstu).name, (*pstu).num, (*pstu).age, (*pstu).group, (*pstu).score);
printf("%s的學號是%d,年齡是%d,在%c組,今年的成績是%.1f!\n", pstu->name, pstu->num, pstu->age, pstu->group, pstu->score);
return 0;
}
運行結果:
#include <stdio.h>
struct stu{
char *name; //姓名
int num; //學號
int age; //年齡
char group; //所在小組
float score; //成績
}stus[] = {
{"Zhou ping", 5, 18, 'C', 145.0},
{"Zhang ping", 4, 19, 'A', 130.5},
{"Liu fang", 1, 18, 'A', 148.5},
{"Cheng ling", 2, 17, 'F', 139.0},
{"Wang ming", 3, 17, 'B', 144.5}
}, *ps;
int main(){
//求數組長度
int len = sizeof(stus) / sizeof(struct stu);
printf("Name\t\tNum\tAge\tGroup\tScore\t\n");
for(ps=stus; ps<stus+len; ps++){
printf("%s\t%d\t%d\t%c\t%.1f\n", ps->name, ps->num, ps->age, ps->group, ps->score);
}
return 0;
}
運行結果:
Name Num Age Group Score Zhou ping 5 18 C 145.0 Zhang ping 4 19 A 130.5 Liu fang 1 18 A 148.5 Cheng ling 2 17 F 139.0 Wang ming 3 17 B 144.5
#include <stdio.h>
struct stu{
char *name; //姓名
int num; //學號
int age; //年齡
char group; //所在小組
float score; //成績
}stus[] = {
{"Li ping", 5, 18, 'C', 145.0},
{"Zhang ping", 4, 19, 'A', 130.5},
{"He fang", 1, 18, 'A', 148.5},
{"Cheng ling", 2, 17, 'F', 139.0},
{"Wang ming", 3, 17, 'B', 144.5}
};
void average(struct stu *ps, int len);
int main(){
int len = sizeof(stus) / sizeof(struct stu);
average(stus, len);
return 0;
}
void average(struct stu *ps, int len){
int i, num_140 = 0;
float average, sum = 0;
for(i=0; i<len; i++){
sum += (ps + i) -> score;
if((ps + i)->score < 140) num_140++;
}
printf("sum=%.2f\naverage=%.2f\nnum_140=%d\n", sum, sum/5, num_140);
}
運行結果: