结构struct数组

结构体struct也是一种数据类型,它也可以作为数组元素的类型

结构数组定义

定义形式:

struct 结构名称{

        成员列表

}数组名称[元素个数];

struct Student{
    char name[20];
    short num;
    float score;
}sar[2]; //有2两个元素的结构数组

结构数组初始化: 

    struct Student{      //Student为结构体名称
        char name[20];  //学生姓名
        int num;       //学生学号
        float score;   //学生成绩
    };
    //定义并初始化
    struct Student st[4] = { //只给st第1、2个元素赋值
        {"王二狗", 1001123, 68.5},
        {"李小花", 1001125, 76.2}
    };

    //指定元素赋值(须强制转换以区分数组)。给第3个元素赋值
    st[2] = (struct Student){
        "张四",
        1001126,
        98
    };

    //成员逐个赋值。给第4个元素赋值
    strcpy(st[3].name, "陈六");
    st[3].num = 1001127;
    st[3].score = 50.5;

    //st长度
    int len = sizeof(st) / sizeof(struct Student);
    printf("st size:%zu\n", sizeof(st));
    for(int i = 0; i < len; i++){
        printf("姓名:%s\t学号:%d\t成绩:%f\n", st[i].name, st[i].num, st[i].score);
    }


#include <stdio.h>
#include <string.h>
/*
时间:2022-05-11 18:47
作者:sgbl888
功能:结构数组
知识点:
    1、
    2、
    3、
*/
struct Student{      //Student为结构体名称
    char name[20];  //学生姓名
    int num;       //学生学号
    float score;   //学生成绩
};
int main(){
    //定义并初始化
    struct Student st[4] = { //只给st第1、2个元素赋值
        {"王二狗", 1001123, 68.5},
        {"李小花", 1001125, 76.2}
    };

    //指定元素赋值(须强制转换以区分数组)。给第3个元素赋值
    st[2] = (struct Student){
        "张四",
        1001126,
        98
    };

    //成员逐个赋值。给第4个元素赋值
    strcpy(st[3].name, "陈六");
    st[3].num = 1001127;
    st[3].score = 50.5;

    //st长度
    int len = sizeof(st) / sizeof(struct Student);
    printf("st size:%zu\n", sizeof(st));
    for(int i = 0; i < len; i++){
        printf("姓名:%s\t学号:%d\t成绩:%f\n", st[i].name, st[i].num, st[i].score);
    }

    return 0;
}

 运行结果:

st size:112
姓名:王二狗     学号:1001123   成绩:68.500000
姓名:李小花     学号:1001125   成绩:76.199997
姓名:张四       学号:1001126   成绩:98.000000
姓名:陈六       学号:1001127   成绩:50.500000

  • 6
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值