聚合型別總結——結構體,列舉,聯合體
阿新 • • 發佈:2019-02-18
相關知識點如圖所示:
結構體重點知識點總結
1、結構體的特殊宣告:
struct //匿名結構體
{
int a;
int b;
float c;
}x;
struct
{
int a;
int b;
float c;
}a[20], *p;
int main() {
p = &x; //警告,兩個宣告的型別不同,所以是非法的
2、結構體的不完整宣告:
struct B;//預設後,編譯器智慧時可以編譯成功
struct A
{
int a;
int b;
struct B;
};
struct B
{
int a;
int b;
struct A;
};
3、結構體成員訪問:
struct A
{
int a;
int b;
struct B;
}x;
int main() {
struct A x;
x.a = 20; //變數名加.訪問變數
4、結構體的自引用:
typedef struct A
{
int a;
int b;
struct A* c;
}x;
5、結構體的記憶體對齊:
struct s2
{
char a;//1
int b;//4
};//4 --8
struct s4{
char a;//1+7
struct s3 {
double d;//8
char b[3];//1->3+1
int i;//4 ->16
};//8->16+1+7
char j[3];//1->24+3+1
char *c[2];//4->28+8+4
double e;//8->48
struct s2 f[2];//4->48+16
char g;//1->65
};//65 不能整除結構體S4中最大對齊數,結果為72
int main() {
printf("%d\n",sizeof(struct s4));//72
位段(位元位)
struct A
{
int a : 2;
int b : 5;
int c : 6;
};//位段大小為1
列舉的使用
enum color
{
RED=100,
GREEN,
blue,
YELLOW
}c;
int main(){
enum color c;
c= RED ;
printf("%d %d %d\n", RED,GREEN,YELLOW);//100 101 103
聯合與共同體的巧妙使用
簡單實現整型轉換成字串
union ip_addr
{
unsigned long addr;
struct
{
unsigned char c1;
unsigned char c2;
unsigned char c3;
unsigned char c4;
}ip;
};
int main() {
union ip_addr my_ip;
my_ip.addr = 176238749;
printf("%d %d %d %d\n", my_ip.ip.c4, my_ip.ip.c3, my_ip.ip.c2, my_ip.ip.c1 );
//10 129 48 157
system("pause");
}