1. 程式人生 > 其它 >C語言 struct(結構體)小結

C語言 struct(結構體)小結

技術標籤:C/C++

C語言結構體

今天有個同學請叫我,C語言 結構體 的內容。也是好久沒碰了,算給自己複習了,也希望可以幫助大家。下面我們 言歸正傳。

  1. 基本結構

    // {} 後的 ; 也是基本結構中的,不能省略
    struct student {
        // 屬性定義。。。 
    };
    
  2. 建立 結構體 時候 ,同時定義變數

    // 定義了 wang 和 students[] 兩個 變數
    struct students {
        char *name;
        int number;
    } wang, students[3];
    

問題來了,定義後的結構體 是什麼型別?定義後的 型別是 struct student

, 如下面例子所示:

struct student students[3];
struct student wang;

是不是覺得 struct student 型別太長了,好彆扭。那麼給大家介紹個 好東西 typedef,它的作用是給結構體 起一個小名,比如:

typedef struct student {
    // 屬性定義。。。 
} T_student;
T_student wang;
T_student students[5];

此時就有兩種表示方法來表示剛剛定義的結構體:

T_student;
struct students;

樣例:

/*
利用一個結構體編寫一個程式,設計5個學生的資訊,資訊包括:姓名、學號、成績。其中每個學生的成績包括三門成績,計算每個學生的三門成績的平均成績,並列印。
*/
#include<stdio.h> #define SIZE (5) typedef struct student { char name[20]; int number; double score[3]; double avarge; } T_student; void input(T_student []); void output(T_student []); int main(void) { T_student students[SIZE]; input(students); output(students); return 0; } void output
(T_student students[]) { printf("print students informaion:\n"); int i; for (i = 0; i < SIZE; i++) { printf("%s %d %.2f %.2f %.2f %.2f\n", students[i].name, students[i].number, students[i].score[0],students[i].score[1],students[i].score[2],students[i].avarge); } putchar('\n'); } void input(T_student students[]) { printf("please input students data:\n"); int i; for (i = 0; i < SIZE; i++) { scanf("%d", &students[i].number); scanf("%s", students[i].name); double sum = 0.0; int j; for (j = 0; j < 3; j++) { scanf("%lf", &students[i].score[j]); sum += students[i].score[j]; } students[i].avarge = sum / 3; } }