指针学完了,来学学结构体吧,走进了一个新的世界。
结构体:不同的数据类型组成的一个结构
一般形式:struct 结构体名
{成员表列};
声明:类型名 成员名
定义的方法:
先声明结构体类型,再定义该类型的变量
struct student
{
int age;
char name[20];
};//不要忘了末尾的';',结构体的声明
struct student student1;//定义
在声明的时候同时定义变量
struct student
{
int age;
char name[20];
}student1;
不指定类型名直接定义结构体变量(没有结构体名,不能再去定义其他结构体变量)
strcut
{
int age;
char name[20];
}zhangsan;
要点:结构体变量的赋值和引用(结构体名,变量名)
结构体数组:数组的每个元素由结构体组成
看代码:定义个结构体数组然后打印
#inlcude<stdio.h>
struct people
{
int age;
char name[20];
}student[2]={18,"zhangdan",19,"lisi"};//定义结构体输组,声明定义一起完成
int main()
{
for(int i=0;i<2;i++)
{
printf("%d,%s",student[i].age,student[i].name);
}
return 0;
}
打印:18,zhandgan
19,lisi
声明和定义分开时:
struct people
{
int age;
char name[20];
};
struct people student[2]={18,"",19,"lisi"};
结构体指针:指针向结构体类型的指针变量(要注意其类型)
看代码:
#include<stdio.h>
struct people
{
int age;
char name[20];
};
int main()
{
struct people people1={18,"lisi"};//定义结构体变量
struct people *p=&people;//定义结构体指针,并赋予people1的地址,注意指针类型为结构体类型
printf("%d,%s\n",people1.age,people1.name);//结构体变量名引用
printf("%d,%s\n",p->age,p->name);//指针引用
return 0;
}
结构体变量和结构体指针作为函数的参数:
#include<stdio.h>
struct people
{
int age;
char name[20];
};
struct student
{
int age;
char name[20];
}gs[2]={15,"zhandgan",16,"lisi"};
int print1(strcut people peopleN)//传入结构体变量
{
printf("%d,%s\n",peopleN.age,people.name);
return 0;
}
int print2(struct student[])//传入结构体数组
{
for(int i=0;i<2;i++)
{
printf("%d,%s\n",gs[i].age,gs[i].name);
return 0;
}
}
int print3(struct people *p1)//传入结构体指针
{
printf("%d,%s\n",p1->age,p1->name);
return 0;
}
int main()
{
struct people people1={18,"lisi"};
strcut people *p=&people1;//定义结构体指针并赋值
print1(people);
print2(gs);
print3(p);
return 0;
}
全部打印出对应的值。
好了,结构体到这里就告一段落了,以后再学。