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

C 語言進階:枚舉與結構體完整指南

     編輯:關於C

一、枚舉:具名整數常量的優雅定義

基本語法與自動編號

enum Color { RED, YELLOW, GREEN, NUM_COLORS };
  • 枚舉常數型別為 int,預設從 0 遞增。
  • 可指定初值:enum { RED=1, YELLOW, GREEN=5 },後續繼續遞增。
  • 末尾常用 NUM_COLORS 取得元素總數,便於陣列邊界檢查。

實戰範例:顏色選單

enum Color { RED, YELLOW, GREEN, NUM_COLORS };
char *names[NUM_COLORS] = { "red", "yellow", "green" };
int choice; scanf("%d", &choice);
if (choice >= 0 && choice < NUM_COLORS) printf("You chose %s\n", names[choice]);

二、結構體:異構資料的聚合封裝

宣告與實例化的多種形式

// 具名結構標籤,後續可複用
struct Point { int x, y; };
struct Point p1, p2;

// 匿名結構直接定義變數,無法複用型別
struct { int x, y; } p3, p4;

成員存取與整體運算

  • 成員存取:p1.x = 10; p1.y = 20;
  • 整體賦值:p1 = p2;(逐成員複製)
  • 複合字面量初始化(C99):p1 = (struct Point){5, 10};
  • 指定初始化器(C99):struct Date d = {.month=4, .year=2025};

結構指標與 -> 運算符

struct Date today = {4, 26, 2025};
struct Date *p = &today;
p->month = 5;  // 等價於 (*p).month = 5;

注意:結構變數名不是地址,必須用 & 取址。

結構體作為函數參數:傳值與傳址

  • 傳值:函數內建立副本,修改不影響原物件,適合小型結構。
  • 傳址:傳遞指標,避免複製開銷,可修改原物件,配合 const 防誤改。
// 傳值範例:計算明天日期
struct Date tomorrow(struct Date d) { ... }

// 傳址範例:修改原物件
void advance_day(struct Date *d) { ... }

進階佈局:結構陣列、巢狀結構、嵌套結構

struct Date dates[100] = { {4,5,2025}, {12,25,2025} };  // 結構陣列

struct DateTime { struct Date d; struct Time t; };     // 巢狀結構(成員為結構)

struct Rect { struct Point pt1, pt2; };                 // 嵌套結構
struct Rect r; r.pt1.x = 1;  // 多層成員存取

完整實戰:日期時間處理與排序

文中包含完整可編譯範例:

  • 日期結構體與明天計算(含閏年判斷)
  • 時間結構體陣列與秒數遞增演示
  • 指標操作結構體陣列的輸入/輸出/列印

所有範例均附帶輸出結果,便於驗證理解。

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