天天看點

typedef原來如此簡單

1、typedef的作用是:對原來的資料類型,再起一個名字。注意,原來的資料類型名還是可以使用的。

方式一:不使用typedef:
int i = 10;

方式二:使用typedef:
typedef int mycnt;
mycnt i = 10;

注意一:方式一和方式二是等價的;
注意二:雖然我們在方式二中為int起了個新名字“mycnt”,但我們還是仍然可以繼續使用"int i = 10;"語句的。
           

2、結構體使用typedef(進而使得代碼更簡潔)

2.1

typedef struct Student
{
	 int sid;
	 char name[100];
	 char sex;
} STU; //給struct Student 起了别名STU,簡潔了代碼
int main()
{
	STU st;//STU st就相當于struct Student st	
}
           

2.2

typedef struct Student
{
	 int sid;
	 char name[100];
	 char sex;
} * PSTU; //PSTU就相當于struct Student *
int main()
{
	struct Student st;
	PSTU st1 = &st;//PSTU st1就相當于struct Student * st1 ,即st1是一個指針變量	
	st1->sid = 99;
}
           

2.3

我們可以把2.1、2.2合起來使用,即

typedef struct Student
{
	 int sid;
	 char name[100];
	 char sex;
}STU,* PSTU; 
int main()
{
	STU st;
	PSTU st1 = &st;
	st1->sid = 99;
}
           

繼續閱讀