结构体就是一些值的集合,但是数组也是一些值的集合,但是结构体里的值的类型是可以不一样的,就比如说一个结构体里可以同时有char, int, short, long。
但是数组总不能说第一个元素放int第二个又放char类型吧,所以结构体是一些不同类型的值的集合。
下面就举个创建结构体类型的例子
#include<stdio.h>
struct book //定义一本书
{
char name[20]; //书名
int page; //页数
};
怎么样简单吧,
那我们该如何使用它创建结构体变量呢?
一样上代码说明
#include<stdio.h>
struct BOOK //定义一本书
{
char name[20]; //书名
int page; //页数
};
int main()
{
struct BOOK book; //结构体关键字+结构体名称+结构体变量名
}
上面这样就是创建了一个结构体变量,
结构体的类型可以是标量,数组,指针,甚至是其他结构体,
但是要注意的是不能自己包含自己的结构体。
包含其他结构体也直接上代码说明
#include<stdio.h>
struct people
{
int age; //年龄、体重、身高、性别
int height;
int weight;
char Gender[10];
};
struct Student //定义一个学生
{
char name[20]; //学生名字
long long num; //学号
struct people a; //其他基本信息
};
那结构体变量该如何赋值呢?
可以像下面这样按顺序赋值
#include<stdio.h>
struct people
{
int age; //年龄、体重、身高、性别
int height;
int weight;
char Gender[10];
};
struct Student //定义一个学生
{
char name[20]; //学生名字
long long num; //学号
struct people a; //其他基本信息
};
int main()
{
struct Student A = { "张三",22222222,{30,120,200,"male"} };
}
也可以一个个赋值
如下面这样
#include<stdio.h>
struct people
{
int age; //年龄、体重、身高、性别
int height;
int weight;
char Gender[10];
};
struct Student //定义一个学生
{
char name[20]; //学生名字
long long num; //学号
struct people a; //其他基本信息
};
int main()
{
struct Student stu;
stu.name[0] = 1;
stu.num = 11111111;
stu.a.age = 80;
stu.a.height = 190;
stu.a.weight = 190;
stu.a.Gender[0] = 1;
}
简单吧
也可以通过scanf自行输入,讲到这顺便讲如何输出。
#include<stdio.h>
#include<string.h>
struct people
{
int age; //年龄、体重、身高、性别
int height;
int weight;
char Gender[10];
};
struct Student //定义一个学生
{
char name[20]; //学生名字
long long num; //学号
struct people a; //其他基本信息
};
int main()
{
struct Student stu;
printf("姓名\n");
gets(stu.name);
printf("学号\n");
scanf("%lld",&(stu.num));
printf("年龄\n");
scanf("%d",&(stu.a.age));
printf("身高\n");
scanf("%d",&(stu.a.height));
printf("体重\n");
scanf("%d",&(stu.a.weight));
getchar("");
printf("性别\n");
gets(stu.a.Gender);
printf("\n\n\n");
printf("%s %lld %d %d %d %s",
stu.name,
stu.num,
stu.a.age,
stu.a.height,
stu.a.weight,
stu.a.Gender
);
}
看看输出结果
结果没问题
张三都这么老了还在上学
我们知道两个数组直接用 = 是不行的,如下,编译器直接报错。
#include<stdio.h>
int main()
{
int a[10];
int b[10];
a = b;
}
但是两个相同的结构体变量是可以的,如下
#include<stdio.h>
#include<string.h>
struct people
{
int age; //年龄、体重、身高、性别
int height;
int weight;
char Gender[10];
};
struct Student //定义一个学生
{
char name[20]; //学生名字
long long num; //学号
struct people a; //其他基本信息
};
int main()
{
struct Student stu = {0};
struct Student stu2 = stu; //直接等于简单粗暴
}
简单吧
关于初识结构体就讲到这啦,如果有什么不好的地方,不懂,错误,都可以说出来我会尽力解答和改正错误。