1.构造类型(由一个或多个已定义的元素用构造方法,构造新的类型)
1)数组类型 相同数据类型
2)结构体类型 不同数据类型
3)公用体类型
2.结构体变量的定义
1)struct Car car1;
2)struct Car{
char *color;
char *name;
}car2,car3;
3)匿名结构体
struct{
char *color;
char *name;
}car4,car5;
3.结构体变量的成员的访问
int main(){
struct Car{
char *color;
int speed;
}
struct Car car1;
//1) strcpy为char *类型结构体变量的成员赋值
strcpy(car1.color,"yellow");
car1.speed="120";
//2)定义结构体变量的时候为成员赋值
struct Car car2={" red",100};
//3)为某一个成员赋值
struct Car car2={.color="blue"};
return 0;
}
4.结构数组,存大量结构相同的结构体变量 int main(){
struct Boy{
char *name;
int age;
}boy[5];
boy[0]~boy[4]具有相同的成员结构
5.结构数组的初始化
1)定义的同时初始化
int main(){ struct Boy{
char *name;
int age;
}boy[5]={{"L",25},{"P",14},{"D",18},{"S",25},{"A",23}};
2)先定义后初始化,整体赋值
int main(){
struct Boy{
char *name;
int age;
};
struct Boy boy[2];
//等号左右两侧类型要一致
boy[0]=(struct Boy){"A",18};
boy[1]=(struct Boy){"B",23};
6.思考:用结构体实现简单通讯录
#include <stdio.h>
#include <stdlib.h>
#define N 10
int main(){
struct Address{
char * name;
char * phoneNum;
}person[N];
printf("请输入联系人姓名:\n");
for (int i=0; i<N; i++) {
scanf("%s",person.name);
scanf("%s",person.phoneNum);
}
for (int i=0; i<N; i++) {
printf("姓名:%s,电话号码:%s\n",person.name,person.phoneNum);
}
return 0;
}
7.结构体的嵌套
1)嵌套其他结构体的变量
struct Date{
int year;
int month;
int day;
};
struct Student{
char *name;
struct Date birthday;
};
2)嵌套自己类型的指针
int main(){
struct Person{
char *name;
int age;
struct Person *child;
};
struct Person kim={"kim",8,NULL};
struct Person p={"林志颖",38,&kim};
printf("%s的儿子是%s\n",p.name,(*(p.child)).name);
return 0;
}
8.结构指针作为函数的参数
struct Car{
char *name;
int speed;
};
void NewCar(struct Car *p){
strcpy(*p.name,"奥拓" );
p.speed=100;
}
int main(){
struct Car car1={"奔驰",120};
NewCar(&car1);
printf("car1.name=%s,car1.speed=%d",car1.name,car1.speed);
return 0;
}
|
|