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可以使用(只对齐某一个字段)
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值