轉自:http://hi.baidu.com/gubuntu/blog/item/70d8d16079535eda8cb10d8e.html
C++中使用:
struct test
{
int x, y;
};
就可以定義一個名為test的結構體,但C中很可能編譯通不過。C語言並不支持在struct后使用標示符定義結構體的名字,test將會被忽略,這相當於定義了一個沒有名字的結構體。C里面 struct test 這才是一個結構體的名字,聲明一個對象時,struct是不能漏的若定義一個該結構體對象test mt; 將會提示未定義的test錯誤信息。所以,在C語言中,一般使用typedef來定義結構體,上面的例子可以改為:
typedef struct _test{
int x, y;
}test;
_test要不要都可以。並且,第一個大括號不能像原來那樣隨便的換行寫(因為是typedef)。
具體可以參考下面的文章。
>>typedef 使用大全(結構體)<<
#define S(s) printf("%s\n", #s); s
typedef struct _TS1{
int x, y;
} TS1, *PTS1, ***PPPTS1; // TS1是結構體的名稱,PTS1是結構體指針的名稱
// 也就是將結構體struct _TS1 命名為TS1,
// 將struct _TS1 * 命名為 PTS1
// 將struct _TS1 *** 命名為 PPPTS1
typedef struct { // struct后面的結構體說明也可以去掉
int x, y;
} TS2, *PTS2;
typedef PTS1 *PPTS1; // 定義PPTS1是指向PTS1的指針
typedef struct _TTS1{
typedef struct ITTS1 {
int x, y;
} iner;
iner i;
int x, y;
} TTS1;
//結構體內部的結構體也一樣可以定義
typedef TTS1::ITTS1 ITS1;
void test_struct()
{
// 基本結構體重定義的使用
TS1 ts1 = {100, 200};
PTS1 pts1 = &ts1; // 完全等價於TS1* pts1 = &ts1;
PPTS1 ppts1 = &pts1; // 完全等價於TS1** ppts1 = &pts1;
PPPTS1 pppts1 = &ppts1; // 完全等價於 TS1*** pppts1 = &ppts1;
TS2 ts2 = {99, 88};
PTS2 pts2 = &ts2; // 完全等價於 TS2* pts2 = &ts2;
TTS1 itts1 = {{110, 220}, 10, 20};
Its1* rits1 = &itts1.i;
ITS1* &its1 = rits1; // 等價於 TTS1::ITTS1 *its1 = &(itts1.i);
printf("ts1\t = (%d, %d)\n*pts1\t = (%d, %d)\n"
"**ppts1\t = (%d, %d)\n***pppts1= (%d, %d)\n\n",
ts1.x, ts1.y, pts1->x, pts1->y,
(**ppts1).x, (**ppts1).y, (***pppts1).x, (***pppts1).y);
printf("ts2\t = (%d, %d)\n*pts2\t = (%d, %d)\n\n",
ts2.x, ts2.y, pts2->x, pts2->y);
printf("itts1\t = [(%d, %d), %d, %d]\n*its1\t = (%d, %d)\n\n",
itts1.i.x, itts1.i.y, itts1.x, itts1.y, its1->x, its1->y);
S(pts1->x = 119);
S(pts2->y = 911);
S(its1->x = 999);
printf("ts1\t = (%d, %d)\n*pts1\t = (%d, %d)\n"
"**ppts1\t = (%d, %d)\n***pppts1= (%d, %d)\n\n",
ts1.x, ts1.y, pts1->x, pts1->y,
(**ppts1).x, (**ppts1).y, (***pppts1).x, (***pppts1).y);
printf("ts2\t = (%d, %d)\n*pts2\t = (%d, %d)\n\n",
ts2.x, ts2.y, pts2->x, pts2->y);
printf("itts1\t = [(%d, %d), %d, %d]\n*its1\t = (%d, %d)\n\n",
itts1.i.x, itts1.i.y, itts1.x, itts1.y, its1->x, its1->y);
S((*ppts1)->y = -9999);
printf("ts1\t = (%d, %d)\n**ppts1\t = (%d, %d)\n\n",
ts1.x, ts1.y, (*ppts1)->x, (*ppts1)->y);
S((**pppts1)->x = -12345);
S((***pppts1).y = -67890);
printf("ts1\t = (%d, %d)\n*pts1\t = (%d, %d)\n"
"**ppts1\t = (%d, %d)\n***pppts1= (%d, %d)\n\n",
ts1.x, ts1.y, pts1->x, pts1->y,
(**ppts1).x, (**ppts1).y, (***pppts1).x, (***pppts1).y);
}