c语言:15、结构体
1、结构体定义
结构体定义方式:
//方式1
struct weapon{
char *name;
int price;
};
struct weapon weapon_1 = {18};
weapon_1.name = "asdf";
//方式2
struct weapon2{
char name[20];
int price;
}weapon2_1;
printf("%d \n", weapon2_1.price);
struct weapon2 wp = {"abcccc",123};
//方式3
struct{
char name[20];
int price;
}struct_var;
printf("%d \n",struct_var.price);
配合typedef
定义结构体:
在这里插入代码片
2、结构体初始化与使用
struct weapon{
char name[20];
int atk;
int price;
}
struct weapon weapon_1 = {"武器1",100,200};
weapon_1.price++;
printf("%s的价格为:%d\n",weapon_1.name, weapon_1.price);
3、结构体数组
struct weapon{
char name[20];
int price;
}
struct weapon weapon_1[2] = {
"武器1",100,
"武器2",200
};
struct weapon weapon_2[2] = {
{"武器1",100},
{"武器2",200}
};
printf("%s的价格为:%d\n", weapon_1[0].name, weapon_1[1].price);
4、结构体指针
指针指向结构体变量
struct weapon{
char name[20];
int price;
};
struct * w;
struct weapon weapon1 = {"武器1", 100};
w = &weapon1;
printf("武器%s的价格是%d\n", (*w).name, (*w).price );
//上下两种访问结构体指针方式等价
printf("武器%s的价格是%d\n", w->name, w->price );
指针指向结构体数组
#include <stdio.h>
struct weapon {
char name[20];
int price;
};
int main(){
struct weapon wea_arr1[2] = {
"倚天剑",200,
"屠龙刀",201
};
struct weapon *p;
p = wea_arr1;
printf("[%s]的价格是[%d]\n", (*p).name, (*p).price );
p++;
printf("[%s]的价格是[%d]\n", p->name, p->price );
return 0;
}
5、结构体内存对齐
typedef struct {
char a;//1
char b;//1
int c;//4
short d;//2
double e;//8
} Align;
Align align = {'a','b',3,4,5.0};
typedef struct {
char a;//1
char b;//1
short d;//2
int c;//4
double e;//8
} Align2;
Align2 align2 = {'a','b',3,4,5.0};
上方例子可以看出,在结构体中将相同的类型连在一起定义能够节省内存。
除了相同类型连在一起定义,不同编辑器,不同c语言版本均定义了不同的内存对齐优化的方式,如:
#pragma pack(2) //基本所有编辑器都支持这种写法,使用后全局生效
struct Person{
char *name
__attribute((aligned(2))) int c;//只有gcc能使用(只对齐某一个字段)
_Alignas(4) int c;//只有c11可以使用(只对齐某一个字段)
}