數組:相同類型變量的集合
struct長度=最後一個成員大小+最後一個成員偏移量+填充值;
結構體中的成員的偏移量需是自身長度的整數倍(不夠就填充);
結構體總長度必須是佔內存最大的成員的長度的整數倍。
三種方式定義結構體:
1.struct weapon{
char name[20];
int atk;
int price;
};
struct weapon weapon_1;
2.1.struct weapon{
char name[20];
int atk;
int price;
}weapon_1;
3.struct {
char name[20];
int atk;
int price;
}weapon_1;
第三種定義方式無法再定義下一個結構體變量了。
結構體初始化:
struct weapon weapon_1={" xxx",xxxx,xx.....};對應的
引用使用.運算符
定義 struct weapon weapon_2[2]={{"m16",50,100},{"m4a1",100,200}};
引用 weapon_2[0].name
結構體數組初始化 struct xxx xx[2] = {{xx, xx, ...}, {yy, yy, ...}};
示例代碼:
#include <stdio.h>
struct weapon{
char name[20];
int atk;
int price;
};
int main(){
int a=0;
float b=0.9;
struct weapon weapon_1={{"weapon_name",100.200};
printf("%s\n,%d\n",weapon_1.name,++weapon_1.price);
struct weapon *w;
w=&weapon_1;
printf("name=%s\n,name=%s\n",(*w).name,w->name);//w->name weapon_1.name
struct weapon weapon_2[2]={{"weapon_name",50.200},{"weapon_name2",100,200}};
printf("%s\n,%d\n",weapon_2[0].name,weapon_2[1].atk);
struct weapon *p;
p=weapon_2;
printf("%s\n",p->name);//p->name weapon_2[0].name
p++;//weapon_2+1 weapon_2[1]
return 0;
}
共用體:作用使幾個不同類型的變量共享同一個內存地址
所佔用的內存空間是成員中最長的一個成員字節數
union data{
int a ;
char b;
int c;
};
int main(){
union data data_1;
data_1.b='c';
data_1.a=10;//則只有最後一個賦值有效
return 0;
}