#include<stdio.h>
#include<string.h>
//利用类型别名typedef 来给结构体另外起一个名字
typedef struct address
{
char *country;
char city[20];
char street[20];
}Address;
//定义别名时,可以把address 省略
/* typedef struct
{
char *country;
char city[20];
char street[20];
}Address; */
//也可以使用一下方法定义结构体别名
struct student
{
int xh;
int age;
char name[20];
char sex[10];
Address addr;
};
typedef struct student ElementType;
typedef struct student* PElementType;
void out_student(struct student stu);
int main()
{
//定义一个结构体,并且初始化
struct student stu1 = {01, 23, "Liao Zinan", "male", {"China", "ChangSha", "Sifang street"}};
struct address stu2_addr = {"China", "Xiangtan", "Baota street"};
struct student stu2 = {01, 23, "Liao Zinan", "male", stu2_addr};
//定义结构体指针
struct student *stup1 = &stu1;
PElementType *stup2 = &stu2;
//结构体成员中的字符型数组的内不可以进行修改例如:city中的内容不可以改为“Xiangtan”,只有通过字符型指针才可以进行修改,直接用 “.”运算符对成员进行修改。
printf("%s\n", stu2_addr.country);
//stu2_addr.city = "Xiangtan";
stu2_addr.country = "Japan";
printf("%s\n", stu2_addr.country);
out_student(stu1);
//定义结构体数组并初始化
printf("===========================\n");
struct student stus[5] = {stu1, {02, 23, "Liao Zinan", "female", {"China", "Xiangtan", "Baota street"}}};
//定义一个指向结构体数组的指针
struct student *stusp = stus;
int i;
for (size_t i = 0; i < 2; i++)
{
out_student(stus[i]);
printf("===========================\n");
}
//定义结构体指针数组
struct student *stups[] = {stup1, stup2};
return 0;
}
void out_student(struct student stu)
{
printf("学生信息如下:\n");
printf("学号:%d\n", stu.xh);
printf("年龄:%d\n", stu.age);
printf("名字:%s\n", stu.name);
printf("性别:%s\n", stu.sex);
printf("家庭地址:\n");
printf("国家:%s\n", stu.addr.country);
printf("城市:%s\n", stu.addr.city);
printf("街道:%s\n", stu.addr.street);
}
类型别名typedef 和 define(下)---结构体和结构体指针声明和定义
最新推荐文章于 2024-11-08 00:52:14 发布