C語言中的結構體提及來接觸的不少,可是工做中本身真正寫的想一想多少?0個?這確實是頗有意思的事情,結構體能夠說是構造數據結構的中心,不過這麼多年的工做中我用到的確實是很少。不過,在PowerPC的驅動編寫中,官方提供的那些數據結構可真是幫了大忙。編程
這段時間一直在接觸Java,接觸面向對象編程,也接觸UNIX以數據爲中心的理論。回頭一想,數據結構確實是值得去仔細研讀一下。在後面的工做中,若有可能仍是把這項技能使用一下。數組
數據結構定義的基本語法:數據結構
struct tag {成員列表}變量列表;編程語言
其實,知道了定義方式再知道成員的訪問方式,基本的技能就描述了一半了。其餘剩下的應該都算得上是使用技巧。ide
若是考慮軟件功能的管理,最好仍是把結構體定義到頭文件中,同時給結構體加上一個tag。這樣不只利於管理,並且還使用方便。指針
關於指針,指向結構體的指針,定義起來也是很簡單的。方法更定義一個普通的方法差很少,只是把數據類型換成tag的名字便可。對象
結構體比數組自由度高不少,結構體的成員能夠相同也能夠不一樣。並且,結構體的成員能夠是任何類型(自己結構體除外,不然無限遞歸),也能夠是其餘的結構體。若是結構體中加入指向結構體的指針成員時,能夠方便地構建出鏈、表、樹等不一樣的數據結構。遞歸
結構體的初始化跟數組的初始化差很少,只是成員肯能不像數組全都是同類型成員,有多是不一樣類型的成員。string
針對結構體經常使用的功能總結,寫代碼以下:it
#include"stdio.h"
#include"string.h"
structtag_demo_result
{
char name[50];
int age;
char sex[10];
int score;
};
typedef structtag_demo_result demo_t,*demo_p_t;
demo_tresult_person1,result_person2;
int main(void)
{
demo_p_t demo_p = NULL;
strcpy(result_person1.name,"ZhangSan");
result_person1.age = 20;
strcpy(result_person1.sex,"male");
result_person1.score = 95;
strcpy(result_person2.name,"LiSi");
result_person2.age = 21;
strcpy(result_person2.sex,"male");
result_person2.score = 93;
demo_p = &result_person1;
printf("name of person1:%s\n",demo_p->name);
printf("age of person1:%d\n",demo_p->age);
printf("sex of person1:%s\n",demo_p->sex);
printf("score of person1:%d\n",demo_p->score);
demo_p = &result_person2;
printf("name of person2:%s\n",(*demo_p).name);
printf("age of person2:%d\n",(*demo_p).age);
printf("sex of person2:%s\n",(*demo_p).sex);
printf("score of person2:%d\n",(*demo_p).score);
return 0;
}
編譯運行結果:
E:\WorkSpace\01_編程語言\01_C語言\exp_06>gcc exp_06.c
E:\WorkSpace\01_編程語言\01_C語言\exp_06>a
name of person1:ZhangSan
age of person1: 20
sex of person1:male
score of person1:95
name of person2:LiSi
age of person2: 21
sex of person2:male
score of person2:93
用到的主要功能以下:
1,結構體的tag;
2,定義結構體數據類型;
3,定義執行結構體的指針數據類型;
4,經過結構體變量訪問結構體成員;
5,經過結構體指針變量訪問結構體成員;
6,結構體指針變量與結構體變量等效使用。
須要注意的一個小細節是,若是是使用告終構體的tag在定義結構體中指向自己結構體類型的指針時是能夠成功的,可是若是沒有tag直接定義一個數據類型將會致使錯誤。具體以下:
代碼1:
#include"stdio.h"
typedef struct{
int a;
demo_t *b;
} demo_t;
int main(void)
{
return 0;
}
上面的代碼在編譯的時候會報錯,由於在定義結構體中指向結構體的成員時結構體的定義尚未完成。爲了可以實現上面的功能,代碼應該修改以下;
#include"stdio.h"
typedef structdemo_tag_t{
int a;
struct demo_tag_t *b;
} demo_t;
int main(void)
{
return 0;
}
編譯結果:
E:\WorkSpace\01_編程語言\01_C語言\exp_06>gcc exp_061.c
E:\WorkSpace\01_編程語言\01_C語言\exp_06>
而這種技術非可是合法的,並且如前面所說,是實現多種數據結構的基礎。