struct stu stu1;
struct 看起來就是多余的,但不寫又會報錯。如果為 struct stu 起了一個別名 STU,書寫起來就簡單了:STU stu1;
這種寫法更加簡練,意義也非常明確,不管是在標准頭文件中還是以後的編程實踐中,都會大量使用這種別名。typedef oldName newName;
oldName 是類型原來的名字,newName 是類型新的名字。例如:typedef int INTEGER; INTEGER a, b; a = 1; b = 2;
INTEGER a, b;等效於int a, b;。typedef char ARRAY20[20];
表示 ARRAY20 是類型char [20]的別名。它是一個長度為 20 的數組類型。接著可以用 ARRAY20 定義數組:
ARRAY20 a1, a2, s1, s2;
它等價於:char a1[20], a2[20], s1[20], s2[20];
注意,數組也是有類型的。例如char a1[20];定義了一個數組 a1,它的類型就是 char [20],這一點已在VIP教程《數組和指針絕不等價,數組是另外一種類型》中講解過。
typedef struct stu{
char name[20];
int age;
char sex;
} STU;
STU 是 struct stu 的別名,可以用 STU 定義結構體變量:
STU body1,body2;
它等價於:struct stu body1, body2;
typedef int (*PTR_TO_ARR)[4];
表示 PTR_TO_ARR 是類型int * [4]的別名,它是一個二維數組指針類型。接著可以使用 PTR_TO_ARR 定義二維數組指針:
PTR_TO_ARR p1, p2;
按照類似的寫法,還可以為函數指針類型定義別名:
typedef int (*PTR_TO_FUNC)(int, int);
PTR_TO_FUNC pfunc;
#include <stdio.h>
typedef char (*PTR_TO_ARR)[30];
typedef int (*PTR_TO_FUNC)(int, int);
int max(int a, int b){
return a>b ? a : b;
}
char str[3][30] = {
"http://c.biancheng.net",
"C語言中文網",
"C-Language"
};
int main(){
PTR_TO_ARR parr = str;
PTR_TO_FUNC pfunc = max;
int i;
printf("max: %d\n", (*pfunc)(10, 20));
for(i=0; i<3; i++){
printf("str[%d]: %s\n", i, *(parr+i));
}
return 0;
}
運行結果:
#define INTERGE int
unsigned INTERGE n; //沒問題
typedef int INTERGE;
unsigned INTERGE n; //錯誤,不能在 INTERGE 前面添加 unsigned
#define PTR_INT int *
PTR_INT p1, p2;
int *p1, p2;
這使得 p1、p2 成為不同的類型:p1 是指向 int 類型的指針,p2 是 int 類型。
typedef int * PTR_INT
PTR_INT p1, p2;