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

C語言 typedef 結構體指標實戰:正確宣告與常見錯誤

     編輯:關於C語言

正確宣告模式

#include <stdio.h>
#include <string.h>

// 推薦:分離結構體標籤與指標別名
typedef struct emp {
    char sex[8];
    char name[15];
    int age;
} *EmpPtr;  // EmpPtr 為指向 struct emp 的指標型別

int main() {
    EmpPtr p;           // 正確:p 為 struct emp*
    // EmpPtr *p;       // 錯誤:這會變成 struct emp**
    
    // 需先配置記憶體
    p = malloc(sizeof(struct emp));
    strcpy(p->sex, "male");
    strcpy(p->name, "zhangfei");
    p->age = 20;
    
    printf("sex: %s\nname: %s\nage: %d\n", p->sex, p->name, p->age);
    free(p);
    return 0;
}

常見錯誤與避坑指南

錯誤 1:同時定義結構體變數與指標別名

// 不推薦:易混淆
typedef struct emp { ... } Emp, *EmpPtr;

建議分開定義,語意更清晰。

錯誤 2:指標變數宣告多加 *

EmpPtr p;      // 正確:p 是指標
EmpPtr *p;     // 錯誤:p 是指標的指標

錯誤 3:未配置記憶體直接解參考

EmpPtr p;
strcpy(p->name, "test");  // 未定義行為:p 未初始化

必須先 malloc 或指向現有物件。

最佳實踐建議

  1. 結構體標籤用 struct TagName
  2. 指標別名用 TagNamePtr 或 PTagName
  3. 物件變數直接用 struct TagName obj
  4. 動態配置記憶體時搭配 malloc/free
// 清晰的分層定義
struct Employee { ... };
typedef struct Employee *EmployeePtr;

struct Employee e1;        // 靜態物件
EmployeePtr e2 = malloc(...); // 動態物件
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved