声明
struct Student{
int id;
char name[20];
char sex;
int age;
double score;
char addr[30];
}(stu1,stu2);
- 关键字:
struct
- 结构体名:开头大写较为规范
- 定义结构体后的分号!!!
- 内部各种类型数据叫做** 成员列表/域表**
- 结构体中成员变量一般不赋具体的值
- stu1,stu2为声明时定义的变量
定义及成员访问
在main中定义变量
int main(){
struct Student stu1; //结构体变量stu1
struct Student stu2 = {1,“helloworld”,"F",17,90,"Xingjiang"};
stu1.id = 777; //.来访问结构体中的成员
stu1.age = 18;
strcpy(stu1.name,"hardworld");
strcpy(stu1.addr,"Tibet");
return 0;
}
struct Student
是一种结构体类型,相当于int, 上代码中定义了两个struct Student类型的变量stu1,stu2- 对结构体变量中成员进行访问使用“.”
- 结构体成员的赋值也可以在变量定义的时候就对其进行初始化
- C99和C11提供了指定初始化器(designated initializer),初始化结构体时使用“.”运算符+成员名进行赋值,对特定的成员进行初始化
struct Student stu1 = {.id=15,.name="hardworld"};
struct Student stu2 = {1,“helloworld”,"F",17,90,"Xingjiang"};
结构体数组
- 结构体类型的数组
- 不是二维数组,因为每个元素的类型不同
- 用法同普通数组
struct Student{
int id;
char name[20];
char sex;
int age;
double score;
char addr[30];
};
int main(){
struct Student stu[3] = { //初始化每个结构体
{1,"helloworld",'F',17,90,"Mohe"},
{2,"hardworld",'F',18,99.5,"Xingjiang"},
{3,"happyworld",'F',16,60,"Nanchang"}
};
for(int i=0;i<3;i++){ //遍历输出结构体数组
printf("id:%d name:%s sex:%c age:%d score:%.2lf address:%s\n",
stu[i].id,stu[i].name,stu[i].sex,stu[i].age,stu[i].score,stu[i].addr);
}
return 0;
}
结构体指针
- 结构体相当于自己建立的类型,声明定义都类似于基础数据类型
- 使用指针对结构体中成员变量访问时使用“->”
- 结构体指针指向结构体变量时,是要用&符取出变量地址,与数组不同(变量名就是数组元素的首地址),但是如果变量是结构体数组,那就可以之直接指向结构体数组变量名(无&),用法同普通类型参数相同,谨记结构体也是一种数据类型即可
- 修改也可以正常的使使用如下
struct Test
{
int a;
char b;
};
int main(){
struct Test gen = {77,'d'}; //定义结构体变量
struct Test *pint = &gen; //定义结构体指针指向结构体变量
printf("%d \t %c\n",gen.a,gen.b); //变量名访问
printf("%d \t %c\n",pint->a,pint->b); //结构体指针间接访问
pint->b = 'S'; //修改数据
printf("%c\n",pint->b);
return 0;
}
输出
77 d
77 d
S
结构体函数
- 就是函数的返回值为定义的结构体类型,用法如同其他类型函数
struct Test{
int No;
char str[20];
};
struct Test chgStr(int* num,struct Test* test){
puts("enter the num:");
scanf_s("%d",num);
test->No = 77;
strcpy(test->str,"hardworld" );
return *test;
}
int main(){
int num = 0;
struct Test pTest = {1,"hardworld"};
printf("num:%d No:%d str:%s b:%d\n",
num,pTest.No,pTest.str);
pTest=chgStr(&num,&pTest);
printf("num:%d No:%d str:%s\n",
num,pTest.No,pTest.str);
return 0;
}
输出
num:0 No:1 str:hardworld b:0
enter the num:
5
num:5 No:77 str:happyworld