结构体是一种结构包含不同的数据类型的成员,用结构体可以实现对一个个体不同的数据进行定义如一个学生的身高,姓名,血型等等,不用结构体的话就只能单纯的用数组进行输入如要输入两个学生的身高就只能定义一个数组分别输入两个数这个学生的身高这个数据也只是存在身高这个数组中(这里边存的都是身高),同理别的数据也是,但要是结构体的话它这里边就是存的是学生的各个不同的数据。
下面就说结构体的定义
定义有几种
1. 先定义结构体类型再定义变量如
#include<stdio.h>
#include<string.h>
void main()
{
struct student//定义结构体
{
charname[10];
inthigh;
intweight;
};
struct studentperson2={"cao",175,60};//定义变量
printf("%s%d\n",person1.name,person1.high);
}
2边定义结构体边定义变量如
#include<stdio.h>
#include<string.h>
voidmain()
{
struct student
{
charname[10];
inthigh;
intweight;
}person2={"cao",175,60};//随带也初始化了为了方便实验
printf("%s%d\n",person2.name,person2.high);
}
3没啥大用就是和第二个一样但是省略了结构体的名字而已如,这样就只能定义一个,但是再想定义结构体的话必须要有结构体的名字了
#include<stdio.h>
#include<string.h>
void main()
{
struct
{
char name[10];
int high;
int weight;
}person2={"cao",175,60};
printf("%s%d\n",person2.name,person2.high);
}
既然说玩了定义就说初始化吧,
初始化有两种第一个是用typedef先对结构体进行改名然后再对结构体行变量的定义如
#include<stdio.h>
#include<stdlib.h>
void main()
{
typedefstruct student
{
char name[10];
int high;
int weight;
}person;
personper1={"cao",175,100};
printf("%s%d\n",per1.name,per1.high);
}
还有这个例子你老是会弄混,字符数组的初始化不能在完成定义后再赋值,下边的是错的ok?
char name[10];
Name=“刁”;这是错误的
#include<stdio.h>
#include<stdlib.h>
void main()
{
typedefstruct student
{
char name[10];
int high;
int weight;
}person;
personper1;
per1.weight=100;
per1.high=175;
printf("%d%d\n",per1.weight,per1.high);
}
2以下为第二种结构体的初始化方法,边定义结构体边定义变量边进行赋值
#include<stdio.h>
#include<string.h>
voidmain()
{
struct student
{
charname[10];
inthigh;
intweight;
}person2={"cao",175,60};//也初始化了为了方便实验
printf("%s%d\n",person2.name,person2.high);
}
3是先定义结构体,再定义结构体变量边进行赋值如
#include<stdio.h>
#include<stdlib.h>
void main()
{
struct student
{
char name[10];
int high;
int weight;
};
struct student per1={"cao",175,100};
printf("%d%d\n",per1.weight,per1.high);
}