C 結構體和共同體

2021-06-28 17:13:10 字數 1735 閱讀 1086

一、定義結構體三種方法:

1.先宣告結構體型別再定義變數名。

2.在宣告型別的同時定義變數。

3.直接定義結構體型別變數。

struct student;

二、共同體

//引用方式:只有先定義了共同體的變數才能引用它。而且不能引用共同體變數,只能引用共同體變數中的成員

union _teacherteacher;

下面上完整**

#include #include struct file;

struct _my;

typedef struct _my file2;

//簡潔寫法

typedef struct _studentstudent;

student * createstudent(char*name,int age)

void deletestudent(student*p)

typedef union _basedatabasedata;

//記憶體優化壓縮

typedef union _data__attribute__((__packed__)) data;

typedef struct _colorargbcolorargb;

typedef union _colorcolor;

int main(int argc, const char * argv) ;

printf("filename=%s,size=%d\n",myfile.name,myfile.size);

student s1 = ;//s1是區域性變數

student s2 = s1;

s2.age = 30;

student *s3 = &s1;

s1.age = 40;

printf("s1.name=%s,s1.age=%d\n",s1.name,s1.age);//訪問成員,直接用.,如果訪問指標的成員,用->

printf("s2.name=%s,s2.age=%d\n",s2.name,s2.age);

printf("s3.name=%s,s3.age=%d\n",s3->name,s3->age);

//物件導向的原型

student *s =createstudent("zhangsan", 20);

printf("name=%s,age=%d\n",s->name,s->age);

deletestudent(s);

// basedata data;

// data.ch = 'b';

// printf("ch_num is %d\n",data.ch_num);

// printf("length of basedata is %ld\n",sizeof(basedata));

printf("length of basedata is %ld\n",sizeof(data));

color c;

c.color = 0xfffe0000;

printf("red=%d\n",c.colorargb.red);

color c1;

c1.color = 0xfffeed2b;

printf("blue=%x\n",c1.colorargb.blue);

return 0;

}

結構體和共同體

結構體適用用是將不同型別的資料成員組合到一起,適用於關係緊密和邏輯相關的資料進行處理 與共同體相比較而言,共同體雖然也能表示不同型別資料的資料集合,但是其資料成員的情形是互斥的,每一時刻只有乙個資料成員起作用,例如乙個人的婚姻狀況,未婚 已婚 離婚,這三個狀態在某一時期只能存在一種情況。struct...

結構體和共同體

結構體 定義多個不同型別的成員變數組合在一起,以實現複雜的資料結構。格式 struct 標籤名 變數1 變數2 或者 typedef struct 標籤名 示例 struct books book 當兩個結構體互相包含,則需要對其中乙個結構體進行宣告 宣告 struct b 結構體a指向結構體b s...

結構體,共同體

共用體 構造資料型別,也叫聯合體 用途 使幾個不同型別的變數共佔一段記憶體 相互覆蓋 結構體是一種構造資料型別 用途 把不同型別的資料組合成乙個整體 自定義資料型別 結構體變數所佔記憶體長度是各成員佔的記憶體長度的總和。共同體變數所佔記憶體長度是各最長的成員佔的記憶體長度。共同體每次只能存放哪個的一...