结构体的嵌套

问题:

从键盘输入学生的信息,并统计学生的成绩

实现

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
//-----------------------------------------------------
/**                       结构体的嵌套              */
//-----------------------------------------------------
struct address {
    char city[64];          // 城市
    char street[64];        // 街道
    int number;             // 门牌号
};

typedef struct address  Address;   // 使用的typedef对类型进行定义
// typedef 是用来定义类型的关键字, 类似的还有下面的使用
typedef unsigned char Byte;        // 一个无符号字符类型的长度为一个字节

/** typedef 可以和结构体的定义一起写。*/
typedef struct name {
    char familyName[32];
    char firstName[32];
}Name;


/** 使用typedef的时候,可以使用的匿名结构体*/
typedef struct scores{                ///注意这个地方struct关键字之后没有名字
    int math;
    int english;
}Scores;

struct student {
    Scores scrs;                /// typedef定义后的可以不用写struct关键字
    struct address addr;
    Name name;
    int age;
};

int calculateTotalScore(struct student  * stdnt)        // 使用结构体指针作为参数
{
    int totalScore = 0;
    totalScore += stdnt->scrs.math;         /// 因为stdnt是指针所有要使用“->”
    totalScore += stdnt->scrs.english;
    return totalScore;

}

测试:

int testStudent()
{
    struct student stdnt;
    strcpy(stdnt.name.firstName, "jack");  /// 数组不能直接赋值,需要拷贝
    strcpy(stdnt.name.familyName, "ma");
    stdnt.scrs.math = 99;
    stdnt.scrs.english = 30;
    strcpy(stdnt.addr.city, "wuhan");
    strcpy(stdnt.addr.street, "guanshan");
    stdnt.addr.number = 100;
    stdnt.age = 20;
    int totalScore = calculateTotalScore(&stdnt);
    printf("totalScore of student %s, is:%d", stdnt.name.familyName,
           totalScore);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

w517565244live

您的支持是我坚持创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值