C语言结构体示例-CSDN博客

92 阅读1分钟

例:打印英雄信息

main.c

#include <stdio.h>
#include <stdlib.h>
#include "hero.h"
extern Hero heros[100];
int main()
{
    Show();
    return 0;
}

hero.h

#ifndef HERO_H_INCLUDED
#define HERO_H_INCLUDED

typedef struct _myTime
{
    int year; int month; int day;
}MyTime;

typedef struct _hero
{
    char name[50];      //英雄名称
    char sex;           //英雄性别
    char job[20];       //英雄职业
    int life;           //英雄生命值
    double speeed;      //攻击速度
    char abillity[20];  //英雄的特殊能力
    MyTime pubTime;     //英雄的上线时间
}Hero;

#endif // HERO_H_INCLUDED

hero.c

#include "Hero.h"

    char name[50];      //英雄名称
    char sex;           //英雄性别
    char job[20];       //英雄职业
    int life;           //英雄生命值
    double speeed;      //攻击速度
    char abillity[20];  //英雄的特殊能力
    MyTime pubTime;     //英雄的上线时间

Hero heros[] = {
    {"影流之主劫", 'm', "刺客", 579, 0.644, "位移", {2012, 8, 15}},
    {"琴瑟仙女霎那", 'F', "法师", 482, 0.644, "减速", {2010, 9, 20}},
    {"疾风剑豪", 'm', "战士", 579, 0.67, "护盾、位移", {2013, 12, 23}}
};

void Show()
{
    //如何知道结构数组的大小呢?
    int len = sizeof(heros) / sizeof(Hero);
    //printf("结构数组的元素个数: %d\n", len);
    int i;
    for(i = 0;i < len; i++)
    {
        printf("%s\t%s\t%d-%d-%d\n", heros[i].name, heros[i].job,
        heros[i].pubTime.year, heros[i].pubTime.month, heros[i].pubTime.day);
    }

}