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

《C和指針》第10章習題解答:結構體定義與位域實戰

     編輯:關於C語言

《C和指針》第10章習題解答:結構體定義與位域實戰

本章重點:結構體嵌套、位域、對齊與內存佈局。

習題 10.1:電話號碼結構體

typedef struct {
    unsigned char QuHao[5];      // 區號
    unsigned char Exchange[10];  // 局號
    unsigned char StnNum[10];    // 用戶號
} TelphoneNumber;

typedef struct {
    unsigned char date[10];
    unsigned char time[10];
    TelphoneNumber UserTelphone;
    TelphoneNumber CallTelphone;
    TelphoneNumber PayTelphone;
} Telphone_Call;

習題 10.2:銷售記錄結構體(多態銷售方式)

typedef struct { float MSRP, ActualPrice, SalesTax, LicenseFee; } CashSale;
typedef struct { float MSRP, ActualPrice, DownPayment, SecurityDeposit, MonthlyPayment; int LeaseTerm; } Rent;
typedef struct { float MSRP, ActualPrice, SalesTax, LicenseFee, DownPayment; int LoanDuration; float InterestRate, MonthlyPayment; char BankName[21]; } LoanSale;

typedef struct {
    char CustomerName[21], CustomerAddr[41], Model[21];
    CashSale CashSal;
    Rent RentSal;
    LoanSale LoanSal;
} SaleRecord;

習題 10.3:機器指令位域結構(PDP-11 風格)

typedef struct { unsigned int dst_reg:3, dst_mode:3, opcode:10; } SingleOperat;
typedef struct { unsigned int dst_reg:3, dst_mode:3, src_reg:3, src_mode:3, opcode:4; } DoubleOperat;
typedef struct { unsigned int offset:8, opcode:8; } Branch;
typedef struct { unsigned int dst_reg:3, dst_mode:3, src_reg:3, opcode:7; } RegistSrc;
typedef struct { unsigned int opcode:16; } MiscCmd;

typedef struct {
    unsigned short addr;
    SingleOperat sgl_op;
    DoubleOperat dbl_op;
    Branch branch;
    RegistSrc reg_src;
    MiscCmd misc;
} machine_inst;

位域自動打包進整數單元,順序視實現定義(通常從低位到高位),跨平台移植需注意端序與填充規則。

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