什么是结构体?
结构体是由一系列具有相同类型或不同类型的数据构成的数据集合,也叫结构。
举个例子:
人就是一个结构体,人的信息有年龄,性别,姓名,身高,体重等,这些信息都是在同一个人身上的,所以存储一个人的信息最好用结构体。
怎么使用结构体?
如何定义结构体?
struct 结构体名称
{
结构体内容
};
#include <stdio.h>
#include <stdlib.h>
//学生结构体
struct student
{
int age;
//年龄
int score;
//成绩
};
void look(const struct student a)
{
printf("年龄:%d 成绩:%d \n",a.age,a.score);
}
int main()
{
struct student a;
//声明一个学生a
a.age = 10;
//通过.的方法修改a的age属性
a.score = 100;
look(a);
return 0;
}
发现我们每次声明一个自己所创造的结构体变量的时候总要先写个struct,这样会降低我们编写代码的效率,所以我们可以在创造结构体类型的时候给它起别名,就要用到typedef这个关键词。然后我们在声明一个结构体变量的时候就可以很简洁了,如下代码。
#include <stdio.h>
#include <stdlib.h>
typedef struct student
{
int age;
int score;
}stu;
//以上是使用typedef给结构体类型起别名的语法
void look(const stu a)
{
printf("年龄:%d 成绩:%d \n",a.age,a.score);
}
int main()
{
stu a;
a.age = 10;
a.score = 100;
look(a);
return 0;
}
如何访问结构体的成员?
访问一般的结构体成员只需要用 . 号即可访问并修改,如果是指针的结构体访问其成员需要用到这个符号 -> 。
#include <stdio.h>
#include <stdlib.h>
//链表的简单代码
typedef struct student
{
int age;
int score;
struct student* next;
// student指针 用来指向下一个student
}stu;
//创造结点函数
stu* create()
{
stu* node = (stu*)malloc(sizeof(stu));
//给node开辟stu的空间大小
node->age = -1;
node->score = -1;
node->next = NULL;
//初始化node的属性
//由于是指针结构体所以需要用->符号访问成员
return node;
}
//查看整张链表函数
void look(stu* head)
{
head = head->next;
//过滤头节点的内容
//因为头节点一般不放置有用信息
while(head)
{
printf("年龄: %d 成绩: %d\n",head->age,head->score);
head = head->next;
}
}
//创造整张链表函数
stu* create_table(int size)
{
stu* head = create();
//创造头节点
stu* ahead = head;
while(size--)
{
stu* newnode = create();
printf("请输入年龄:\n");
scanf("%d",&newnode->age);
printf("请输入成绩:\n");
scanf("%d",&newnode->score);
ahead->next = newnode;
ahead = newnode;
//尾插法
}
return head;
}
int main()
{
int size;
scanf("%d",&size);
stu* head = create_table(size);
look(head);
return 0;
}