结构体
#include <stdio.h>
#include <stdlib.h>
struct dog{
int age;
char name[20];
char favorite[20];
};
//定义结构体类型的同时,取好别名
typedef struct person{
int age;
char name[20];
struct dog pet;
} person;
struct book{
//页数
int pages;
//价格
float prices;
//结构体成员又是一个结构体变量
struct person author;
};
void first(){
puts("----------结构体----------");
//自定义一种数据类型,类型名字叫做 struct person,
//这种类型里面有两个成员,一个age和一个name
//struct book就是一种数据类型,相当于int。a是变量名
struct book a = {252,42.5};//初始化内容,类似数组
struct person b = {28,"Lisa"};//初始化部分内容,类似数组
struct dog c = {2,"大黄","吃骨头"};
b.pet = c;//或者 a.author.pet = c;
a.author = b;//给结构体成员赋值
printf("页数:%d \t 价格:%f \t 作者:%s,作者的宠物的爱好是:%s",
a.pages,a.prices,a.author.name,
a.author.pet.favorite);
}
void second(){
int a = 10;
int b = a;
a = 30;
printf("b = %d\n",b);
struct person lisa = {18,"lisa"};
struct book c_language= {256,52.5};
c_language.author = lisa;
lisa.age = 20;
printf("lisa.age = %d\n",c_language.author.age);
}
/*结构体类型取别名的三种方式:
* 1.定义结构体类型的同时,用typedef取别名
* 2.定义结构体类型后,用typedef取别名
* 3.使用宏定义define,给结构体类型定义宏实现字符替换效果
* */
//#define uchar unsigned char
//类型定义,和上面使用宏定义实现的效果一样
typedef unsigned char uchar;
//#define person struct person
//类型定义,和上面使用宏定义实现的效果一样
//typedef struct person person;
void three(){
person a = {18,"lisa"};
uchar b = 20;
}
/*测试:给下面的结构体取三个别名*/
//第一种方式:使用宏定义
#define A struct student
//第二种方式:typedef类型定义
typedef struct student B;
//第三种方式:typedef类型定义,定义结构体的同时取别名
typedef struct student{
int age;
char name[20];
} C;
void four(){
A a = {18,"lisa"};
B b = {19,"judy"};
C c = {20,"andy"};
printf("%d\t",a.age);
printf("%s\n",a.name);
printf("%d\t",b.age);
printf("%s\n",b.name);
printf("%d\t",c.age);
printf("%s\n",c.name);
}
int main(void) {
four();
second();
return EXIT_SUCCESS;
}