C语言 结构体

#include <stdio.h>

//结构体声明
struct student{
    int num;
    char name[20];
    char sex;
    int age;
    float score;
    char address[100];
};

int main() {
    struct student std1={1000,"vvq",'1',10,99.2,"XiShan"};//定义及初始化
    struct student sarr[4];//结构体数组
    int i;
    std1.num=1005;//可以在打印之前更改
    printf("%d %s %c %d %5.2f %s\n",std1.num,std1.name,std1.sex,std1.age,std1.score,std1.address);//结构体输出必须单独访问每个成员
  //  scanf("%d%s %c%d%f%s",&std1.num,std1.name,&std1.sex,&std1.age,&std1.score,std1.address);//数组名自带地址不需要取地址
    //%c 不会忽略前方缓冲区里的\n需要空格 其他的都会忽略
    printf("--------------------------------------------------------------\n");
    //一个数组下标相当于一个结构体 包含每一个成员
    for (i=0; i<4;i++)
    {
        scanf("%d%s %c%d%f%s",&sarr[i].num,sarr[i].name,&sarr[i].sex,&sarr[i].age,&sarr[i].score,sarr[i].address);
    }

    for(i=0;i<4;i++)
    {
        printf("%d %s %c %d %5.2f %s\n",sarr[i].num,sarr[i].name,sarr[i].sex,sarr[i].age,sarr[i].score,sarr[i].address);
    }
    return 0;
}

 

结构体对齐 --- 高效的取内存上的数据

结构体大小必须是其最大成员的整数倍  大小不算数组

 

最大是int 4个字节

4+20(是4的整数倍)+4(1变成4)+4+4+32(30不是4的整数倍所以加2)=68


 

 练习一下

#include <stdio.h>

struct student_type1{
    double score; 
    short age;
};
struct student_type2{
    double score;
    short age;
    int height;
};//8+8=16
struct student_type3{
    int height;
    short age;
    char sex;
};
int main() {
    struct student_type1 s1;
    struct student_type2 s2;
    struct student_type3 s3;
    printf("student_type1 size=%d\n",sizeof (s1));
    printf("student_type2 size=%d\n",sizeof (s2));
    printf("student_type3 size=%d\n",sizeof (s3));
    return 0;
}

 


 

题解

#include <stdio.h>

struct student_type1{
    double score; //8byte
    short age;//短整型 2 但变成8
};//8+8=16
struct student_type2{
    double score;
    //两个小的和不满8 可以填充在一起 并不是三个8字节
    short age;
    int height;
};//8+8=16
struct student_type3{
    int height; //4字节
    //2和1不满4 填充在一起为4
    short age;
    char sex;
};


int main() {
    struct student_type1 s1;
    struct student_type2 s2;
    struct student_type3 s3;
    printf("student_type1 size=%d\n",sizeof (s1));
    printf("student_type2 size=%d\n",sizeof (s2));
    printf("student_type3 size=%d\n",sizeof (s3));
    return 0;
}

 

 

 

 

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

iwan24leep

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值