#include <stdio.h>
int main(){
//第一种定义方式 struct Dog{int leg1;int head;char *name;}; struct Dog jingHa={4,1,"请叫我小灰"}; printf("%d条腿%d个头,%s\n",jingHa.leg1,jingHa.head,jingHa.name); //打印结果:4条腿1个头,请叫我小灰
//第二种定义方式 struct student{char *name;char *sex;int high;char grade;}classmate={"孙凡","男",175,'a'}; printf("姓名:%s\t性别:%s\t身高:%d\t评分:%c\n",classmate.name,classmate.sex,classmate.high,classmate.grade); //打印结果:姓名:孙凡 性别:男 身高:175 评分:a
//第三种定义方式 //只有在初始化的时候才能批量赋值. //定义好之后只能单个赋值,和数组一样. struct phone{char *name;int price;}apple; apple.name = "我叫6S"; apple.price = 6088; printf("%s,我卖%d元人民币\n",apple.name,apple.price); // 打印结果:我叫6S,我卖6088元人民币
//匿名类型结构体(不定义数据类型名) //注意必须定义的同时初始化. //而且这种结构体定义方式不能重用 struct {char *name;char *whos;int manyPerson;}room={"书房","孙凡",1}; printf("房间名字%s,%s的房间,房间里有%d个人\n",room.name,room.whos,room.manyPerson); //打印结果:房间名字书房,孙凡的房间,房间里有1个人
//嵌套定义 struct wallet{char *name;int size;}; struct bag{char *name;int size;struct wallet mini;}; struct bag backpack = {"双肩背",28,"牛皮小钱包",5}; printf("我是%s,有%d寸大,我里边还有%s%d寸大\n",backpack.name,backpack.size,backpack.mini.name,backpack.mini.size); // 打印结果:我是双肩背,有28寸大,我里边还有牛皮小钱包5寸大
return 0; }
|