C語言學習入門(九)typedef關鍵字
發表時(shí)間:2021-1-10
發布人(rén):融晨科技
浏覽次數:41
關鍵字:typedef
用法:爲(wéi / wèi)各種數據類型定義一個(gè)新名字(别名)
typedef與基本數據類型
typedef int Integer;Integer a= 8;
也(yě)可以(yǐ)在(zài)别名的(de)基礎上(shàng)再起一個(gè)别名
typedef Integer MyInteger;MyInteger a = 8;
原來(lái)的(de)數據類型也(yě)可以(yǐ)正常使用
typedef與指針
typedef char *String;String str = “jackie”;
typedef與結構體
typedefstructPerson Per;// 這(zhè)樣在(zài)定義結構體變量時(shí) 就(jiù)不(bù)用帶上(shàng)struct 關鍵字了(le/liǎo)
Per p; p.name = “xyz”;
定義并取别名:
typedefstruct Student// 結構體名 Student 可以(yǐ)省略
{
int age;
} Stu;
void processStudent()
{
Stu student = {18};
student.age =19;
}
typedef與指向結構體的(de)指針
typedef struct
{
int age;
} Stu;
Stu stu = {20};
typedef Stu *S;//指向結構體的(de)指針 取别名 S
S s = &stu;
typedef struct LNode
{
int data;
struct LNode *next;
} LinkList, *SList;
int main(int argc, const char * argv[])
{
LinkList l = {1, NULL};
LinkList ll = {2, NULL};
l.next = ≪
printf("%d, ", l.next->data);
SList sl = ≪
if (sl->next != NULL)
printf("%d, ", sl->data);
return 0;
}
typedef與枚舉類型
typedef enum
{
…
} Season;
//用法與結構體類似
typedef與指向函數的(de)指針
int sum(int a, int b)
{
return a + b;
}
void main()
{
typedef int (*P)(int a, int b);
P p = sum;
int result = (*p)(3, 5);
return 0;
}
typedef與#define
typedef char *String;
String s = “abc”
#define String char *;
String s = “abc”; //這(zhè)樣使用效果一樣
當 這(zhè)樣使用:
String s1,s2; //用第一種替換: char *s1, char *s2;
String s3,s4; //用第二種替換: char * s3, s4; <==> char *s3, char s4;