在c语言中,可以使用struct存放一组不同类型的数据,如下
struct 结构体名{
//定义不同类型的数据
};
自定义结构体
*注意:大括号后面的;不能少
结构体属于一种数据类型,因此可以对其自定义。
实例如下:
方法一:
整体赋值:
#include<stdio.h>
struct student{
int num;
char name[20];
char sex;
int age;
};
//对结构体成员进行赋值
struct student stu[]={
{10101,"li lin",'M',18},{
10102,"zhang fun",'M',19},{
10103,"zhao yang",'F',20}
};
方法二:逐一赋值:
#include<stdio.h>
#include<string.h>
struct student{
int num;
char name[20];
char sex;
int age;
}stu1;
int main(){
//逐一赋值
stu1.num=10101;
//使用strcpy对字符串进行赋值
strcpy(stu1.name,"li lin");
stu1.sex='M';
stu1.age=20;
printf("%d %s %c %d\n",stu1.num,stu1.name,stu1.sex,stu1.age);
return 0;
}
*注意:1.自定义结构体中的数据要与student中的数据类型相对应。
2.对字符串进行赋值时不能使用普通的赋值方式,而要引用<string.h>使用strcpy函数进行赋值。
如何对定义的结构体实现遍历?
这里结合指针知识进行遍历:
#include<stdio.h>
struct student{
int num;
char name[20];
char sex;
int age;
};
//stu[]维数可以不写,计算机可以识别出
struct student stu[]={
{10101,"li lin",'M',18},{
10102,"zhang fun",'M',19},{
10103,"zhao yang",'F',20}
};
int main(){
#引入结构体student的指针p
struct student* p;
for(p=stu;p<stu+3;p++){
printf("%d %s %c %d\n",p->num,p->name,p->sex,p->age);
}
return 0;
}