C语言给结构体赋数据值和带有结构体指针变量的赋值方法

C/C++ 专栏收录该内容
60 篇文章 3 订阅

C语言给结构体赋数据值

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Student //声明结构体类型Student
{
    int num;
    char name[20];
    char sex;
    int age;
};

//下面给结构体赋数据值
struct Student stu[5] =
    {
        {10101, "Zhou ping", 'M', 15}, //定义结构体数组并初始化
        {10102, "Zhang ping", 'M', 15},
        {10103, "Liou fang", 'F', 16},
        {10104, "Cheng ling", 'F', 17},
        {10105, "Wang ming", 'M', 15}};

int main()
{
    struct Student *ps; //定义指向struct Student结构体类型数据的指针变量
    printf("No\tName\t\t\tSex\tage\t\n");
    for (ps = stu; ps < stu + 5; ps++)
        printf("%d\t%s\t\t%c\t%d\t\n", ps->num, ps->name, ps->sex, ps->age);
    return 0;
}

执行结果:

No	Name			Sex	age
10101	Zhou ping		M	15
10102	Zhang ping		M	15
10103	Liou fang		F	16
10104	Cheng ling		F	17
10105	Wang ming		M	15
[Thread 5812.0x69b0 exited with code 0]
[Inferior 1 (process 5812) exited normally]

C语言结构体指针变量作函数参数

#include <stdio.h>
struct stu
{
    int num;
    char *name;
    char sex;
    float score;
} boy[5] = {
    {101, "Li ping", 'M', 45},
    {102, "Zhang ping", 'M', 62.5},
    {103, "He fang", 'F', 92.5},
    {104, "Cheng ling", 'F', 87},
    {105, "Wang ming", 'M', 58}};

void Fve(struct stu *ps)
{
    int c = 0, i;
    float ve, s = 0;
    for (i = 0; i < 5; i++, ps++)
    {
        s += ps->score;
        if (ps->score < 60)
            c += 1;
    }
    printf("s=%f\n", s);
    ve = s / 5;
    printf("average=%f\ncount=%d\n", ve, c);
}

main()
{
    struct stu *ps;
    void Fve(struct stu * ps);
    ps = boy;
    Fve(ps); 
}

执行结果:

s=345.000000
average=69.000000
count=2
[Thread 30236.0xa0b0 exited with code 26]
[Inferior 1 (process 30236) exited with code 032]
  • 0
    点赞
  • 0
    评论
  • 3
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 鲸 设计师:meimeiellie 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值