首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C語言結構體入門:定義、宣告、成員存取與巢狀結構全解析

     編輯:關於C語言

前言:為什麼需要結構體?

陣列要求所有元素型別相同,但現實資料往往異質:學生資料包含姓名(字串)、學號(整數)、性別(字元)、成績(浮點數)。結構體(struct)正是為此而生——將不同型別的變數聚合為單一邏輯單元。

一、結構體定義與變數宣告三種寫法

1. 先定義標籤,再宣告變數(推薦,利於複用)


struct Student {
    char name[20];
    int id;
    char sex;
    float score;
};

struct Student stu1, stu2;  // 宣告兩個變數

2. 定義同時宣告


struct Student {
    char name[20];
    int id;
    char sex;
    float score;
} stu1, stu2;

3. 匿名結構體(一次性使用)


struct {
    char name[20];
    int id;
    char sex;
    float score;
} stu1, stu2;  // 無標籤,無法在別處復用此型別

二、成員存取:. 運算子


struct Student stu;
strcpy(stu.name, "Zhang San");
stu.id = 2024001;
stu.sex = 'M';
stu.score = 92.5;

printf("%s, %d, %c, %.1f\n", stu.name, stu.id, stu.sex, stu.score);

三、結構體陣列:批量管理同類資料


struct Student class[50];  // 50 位學生

for (int i = 0; i < 50; ++i) {
    printf("輸入第 %d 位學生: ", i+1);
    scanf("%s %d %c %f", class[i].name, &class[i].id, &class[i].sex, &class[i].score);
}

四、巢狀結構體:建立層級資料模型


struct Date {
    int year, month, day;
};

struct Student {
    char name[20];
    int id;
    struct Date birthday;  // 巢狀結構體
    float score;
};

struct Student stu;
stu.birthday.year = 2000;
stu.birthday.month = 5;
stu.birthday.day = 15;
// 存取路徑:stu.birthday.year

五、結構體初始化

C89 風格(順序對應)


struct Student stu = {"Li Si", 2024002, 'F', 88.0};

C99 指定初始化器(推薦,可跳過欄位、順序不拘)


struct Student stu = {
    .name = "Wang Wu",
    .id = 2024003,
    .score = 95.5,
    .sex = 'M'
};

六、結構體大小與對齊


struct Demo {
    char c;   // 1 byte
    // 3 bytes padding
    int i;    // 4 bytes
    double d; // 8 bytes
};            // sizeof = 16 (對齊到 8)
  • 編譯器為滿足 CPU 存取對齊要求,在成員間插入填充位元組
  • 可用 #pragma pack(n) 控制對齊(非標準,影響可移植性)
  • 將大型別成員放在前面可減少填充

七、常見操作模式

操作範例
指標存取struct Student *p = &stu; p->id = 100;
整體賦值struct Student a = b;(淺拷貝,指標成員共用記憶體)
比較無內建比較,需逐成員比較或 memcmp(注意填充位元組)
函數參數大型結構體傳指標 void func(const struct Student *s)
函數返回可直接返回結構體值(C99 保證),或返回指標(需管理生命週期)

八、typedef 簡化宣告(業界慣例)


typedef struct {
    char name[20];
    int id;
    char sex;
    float score;
} Student;  // 直接用 Student 當型別名

Student stu1, stu2;

結語

結構體是 C 語言建立抽象資料型別的基石。掌握「定義標籤、宣告變數、. 存取成員、巢狀建模、指定初始化、對齊意識」六大核心技能,並配合 typedef 簡化代碼,即可輕鬆驅動從學生管理系統到嵌入式協定解析的各類實戰專案。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved