c语言类型struct结构体的使用

在c语言中,可以使用struct存放一组不同类型的数据,如下

struct 结构体名{
//定义不同类型的数据
};
自定义结构体

*注意:大括号后面的;不能少

结构体属于一种数据类型,因此可以对其自定义。

实例如下:

方法一:

整体赋值:

#include<stdio.h>
struct student{
        int num;
        char name[20];
        char sex;
        int age;
    };
//对结构体成员进行赋值
struct student stu[]={
    {10101,"li lin",'M',18},{
     10102,"zhang fun",'M',19},{
     10103,"zhao yang",'F',20}
};

方法二:逐一赋值:


#include<stdio.h>
#include<string.h>
struct student{
        int num;
        char name[20];
        char sex;
        int age;
    }stu1;
int main(){
    //逐一赋值
    stu1.num=10101;
    //使用strcpy对字符串进行赋值
    strcpy(stu1.name,"li lin");
    stu1.sex='M';
    stu1.age=20;
    
    printf("%d %s %c %d\n",stu1.num,stu1.name,stu1.sex,stu1.age);
    return 0;
}

*注意:1.自定义结构体中的数据要与student中的数据类型相对应。

             2.对字符串进行赋值时不能使用普通的赋值方式,而要引用<string.h>使用strcpy函数进行赋值。

如何对定义的结构体实现遍历?

这里结合指针知识进行遍历:

#include<stdio.h>
struct student{
        int num;
        char name[20];
        char sex;
        int age;
    };
//stu[]维数可以不写,计算机可以识别出
struct student stu[]={
    {10101,"li lin",'M',18},{
     10102,"zhang fun",'M',19},{
     10103,"zhao yang",'F',20}
};
int main(){
#引入结构体student的指针p
    struct student* p;
    for(p=stu;p<stu+3;p++){
        printf("%d %s %c %d\n",p->num,p->name,p->sex,p->age);
    }
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值