1. 程式人生 > >C語言 一個例子說明結構體變數,結構體陣列和結構體指標

C語言 一個例子說明結構體變數,結構體陣列和結構體指標

輸入三個學生的個人資訊 包含學號 姓名和三門學科的成績
輸出平均成績最高的學生的學號 姓名 各科成績以及平均成績
程式碼如下(譚浩強c程式設計的例子)

#include<stdio.h>

struct Student
{int num;
char name[20];
float score[3];
float aver;
};

int main()
{
    void input(struct Student stu[]);
    struct Student max(struct Student stu[]);
    void print(struct Student stud);
    struct
Student stu[3]; struct Student *p=stu; input(p); print(max(p)); getchar(); getchar(); return 0; } void input(struct Student stu[]) { int i; printf("請依次輸入學生編號,姓名,三個科目成績:\n"); for (i=0;i<3;i++) { scanf("%d %s %f %f %f",&stu[i].num, &stu[i].name, &stu[i].score[0
], &stu[i].score[1], &stu[i].score[2]); stu[i].aver = (stu[i].score[0]+stu[i].score[1]+stu[i].score[2])/3.0; } } struct Student max(struct Student stu[]) { int i,m=0; for (i = 0;i<3;i++) { if(stu[i].aver>stu[m].aver) m = i; } return stu[m]; } void print(struct
Student stud) { printf("成績最高的學生:\n"); printf("學號:%d\n 姓名:%s\n 三門成績:%5.1f,%5.1f,%5.1f\n 平均成績:%6.2f\n",stud.num,stud.name,stud.score[0],stud.score[1],stud.score[2],stud.aver); getchar(); }

程式執行結果如下:
這裡寫圖片描述

定義一個結構體:

struct Student
{int num;
char name[20];
float score[3];
float aver;
};

結構體的作用與int double float等一樣,都是一種資料型別,只是結構體是將不同型別組合後形成的一個使用者自己定義的資料結構

結構體變數:
該程式定義了一個結構體陣列和一個結構體指標,就像陣列和指標的定義一樣,需要說明陣列和指標的型別,陣列就是可以存放什麼型別的資料,指標是可以指向什麼型別的資料。

struct Student stu[3];
struct Student *p=stu;

用結構體變數和結構體變數的指標做函式的引數:
定義結構體指標p,並初始化它讓他指向結構體陣列stu的首地址。

input函式形參為結構體陣列,實參為結構體指標。
max函式形參為結構體陣列,實參為結構體指標。
print函式形參是結構體變數,實參是結構體變數(是結構體陣列元素)。