目录
一、什么是结构体
**结构体是不同类型数据的集合,把这些不同类型的数据称为结构体的成员。
**c语言只给出了定义结构体类型的方法,具体的结构体类型,需要程序员自己定义,然后使用,所以,结构体是一种自定义数据类型
格式:
struct 结构体标签{
成员类型 成员名;
成员类型 成员名;
.... ...
成员类型 成员名;
};
例如:
struct student{
int sno;
char name[20];
float score;
};
二、定义结构体变量
1.常规定义
struct student{
int sno;
char name[20];
float score;
};
struct student st; //定义一个结构体变量st
2.与类型同时定义
struct student{
int sno;
char name[20];
float score;
}st; //定义一个结构体变量st
3.直接定义
struct {
int sno;
char name[20];
float score;
}st; //定义一个结构体变量st
三、初始化结构体变量
1.完全初始化
struct student st = {1001,"Jack",87.45};
2.部分初始化
struct student st = {1001,"Jack"};
3.指定成员初始化
struct student st = {.name = "Jack",87.45,.sno=1002};
四、给结构体变量赋值
除了初始化之外,结构体变量不能整体赋值,只能分别给每一个成员赋值
例如:
struct student st;
st.sno = 1002;
strcpy(st.name,"Rose");
st.score = 87.45;
同类型结构体变量之间可以相互赋值
struct student s1;
s1 = st;
五、打印结构体变量 ----
//只能分别打印结构体变量中的每一个成员
例如:
#include <stdio.h>
#include <string.h>
//定义结构体类型
struct student{
int sno;
char name[20];
float score;
};
int main(void)
{
//定义结构体变量
struct student st;
struct student s1;
//给结构体变量赋值
st.sno = 1002;
strcpy(st.name,"Rose");
st.score = 87.45;
s1 = st; //同类型结构体之间可以相互赋值
//打印结构体变量的值
printf("%d %s %.2f\n",st.sno,st.name,st.score);
printf("%d %s %.2f\n",s1.sno,s1.name,s1.score);
return 0;
}
六、结构体数组 -----可以保存多个结构体的信息
例如:
#include <stdio.h>
#include <string.h>
//定义结构体类型
struct student{
int sno;
char name[20];
float score;
};
int main(void)
{
int n,i;
printf("请输入元素个数:");
scanf("%d",&n);
//定义结构体变量
struct student st[n];
for(i = 0 ; i < n; i++){
printf("请输入学生信息(sno name score):");
scanf("%d%s%f",&st[i].sno,st[i].name,&st[i].score);
}
printf("-------------------\n");
for(i = 0 ; i < n; i++)
printf("%d %s %.2f\n",st[i].sno,st[i].name,st[i].score);
return 0;
}
七、结构体成员类型
//结构体是不同类型数据的集合。
1.基本类型的成员
struct A{
int a;
float b;
};
2.数组类型的成员
struct student{
int sno;
char name[20];
};
3.结构体类型的成员
#if 0
struct A{
int a;
float b;
};
struct B{
int x;
struct A y; //结构体类型的成员
};
#else
struct B{
int x;
struct{
int a;
float b;
}y;
};
#endif
4.指针类型的成员
1》基本类型指针
struct A{
int a;
int* p;
};
2》函数指针
例如:
参考:struct03.c
3》结构体指针
例1:
struct A{
int a;
float b;
};
struct B{
int x;
struct A *pa; //结构体指针类型的成员
};
int main(void)
{
struct A sa = {100,12.34};
struct B sb = {200,&sa};
printf("sb.x = %d\n",sb.x);
printf("sb.pa->a = %d\n",sb.pa->a);
printf("sb.pa->b = %.2f\n",sb.pa->b);
return 0;
}
例2:
struct B{
int x;
struct B *pb; //结构体指针类型的成员
};
int main(void)
{
struct B b1 = {100,NULL};
struct B b2 = {200,&b1};
struct B b3 = {300,&b2};
struct B b4 = {400,&b3};
struct B b5 = {500,&b4};
struct B b6 = {600,&b5};
struct B *p = &b6;
while(p != NULL){
printf("%d \n",p->x);
p = p->pb;
}
return 0;
}