C语言结构体

基本结构

在这里插入图片描述
注意最后那个大括号后面有分号

#include<stdio.h>
struct student
{
    int id;
    char name;
    struct teacher
    {
        int age;
    }th;
};
int main()
{
    int id=10;
    struct student stu;
    stu.id=6666;
    stu.name='d';
    stu.th.age=18;
    printf("stu.id=%d\nstu.name=%d\nstu.teacher.age=%d\n",stu.id,stu.name,stu.th.age);
    return 0;
}

结构体中也可以有结构体

#include<stdio.h>
struct student
{
    int id;
    char name;
    struct teacher
    {
        int age;
    }th;
}stu;
int main()
{
    int id=10;
    stu.id=6666;
    stu.name='d';
    stu.th.age=18;
    printf("stu.id=%d\nstu.name=%d\nstu.teacher.age=%d\n",stu.id,stu.name,stu.th.age);
    return 0;
}

可以直接在花括号后面直接赋值给结构体一个变量

#include<stdio.h>
struct student
{
    int id;
    char name;
    struct teacher
    {
        int age;
    }th;
};
int main()
{
    int id=10;
    struct student stu={6666,'d',18};
    printf("stu.id=%d\nstu.name=%d\nstu.teacher.age=%d\n",stu.id,stu.name,stu.th.age);
    return 0;
}

也可以用大括号按顺序给结构体中的成员赋值

typedef

#include<stdio.h>
typedef struct student
{
    int id;
    char name;
    struct teacher
    {
        int age;
    }th;
}stu;
int main()
{
    int id=10;
    stu stt;
    stt.id=6666;
    stt.name='d';
    stt.th.age=18;
    printf("stu.id=%d\nstu.name=%d\nstu.teacher.age=%d\n",stt.id,stt.name,stt.th.age);
    return 0;
}

使用typedef可以直接用花括号后面的stu表示一长串的struct student,后面给结构体赋值变量时可简洁一点

结构体数组

结构体数组就是数组里面存放的是结构体

#include<stdio.h>
struct student
{
    int id;
    char name;
}stu[10];
int main()
{
    stu[0].id=20;
    stu[0].name='d';
    stu[1].id=11;
    stu[1].name='p';
    printf("stu[0].id=%d\nstu[0].name=%d\nstu[1].id=%d\nstu[1].name=%d\n",stu[0].id,stu[0].name,stu[1].id,stu[1].name);
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值