结构体概述
声明一个结构体类型的一般形式:
struct student{ //student是结构体名,注意和结构体变量s区分开来
char name[10];
char sex; //这两者都是成员名称
int age;
};
struct student s; //s是结构体变量,"struct student"是结构体类型
定义结构体变量并初始化
struct student{ //student是结构体名,注意和结构体变量s区分开来
char name[10];
char sex; //这两者都是成员名称
int age;
};
//主函数中:
struct student s={"wangming",'m',21};//注意字符数组的定义方法:要加"",字符的定义方法:要加''
结构体的嵌套
struct birthday{
int year;
int mon;
int day;
}; //需要嵌套的结构体
struct student{
char name[10];
char sex;
int age;
struct birthday date1; //嵌套的结构体的使用
};
//主函数中:
struct student s={"wangming",'f',21,{1998,3,9}};//注意嵌套结构体的定义方法:{
{}}
结构体输入,尤其是%c
scanf("%s %c%d",s.name,&s.sex,&s.age) //注意%c输入的时候一定要和%s有一个空格
结构体数组的写法
定义结构体数组并初始化:
法一:
struct student{
char name[10];
char sex;
int age;
}stu[2]={
"hyj",'f',21,"wangming",'m',21};
法二:
struct student{
char name[10];
char sex;
int age;
};
struct student s[2];
法三:在main函数中定义。
练习
题目详情:点击这里
源代码:
#include<bits/stdc++.h>
using namespace std;
struct vegetable{
int hour;
int minute;
}need[10]; //重点关注结构体定义的方式
int main(){
int n;
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d:%d",&need[i].hour,&need[i].minute);
}
struct vegetable now={13,15};
struct vegetable expect[10];
for(int i=0;i<n;i++){
expect[i].hour=(need[i].hour+now.hour)%24;
if((need[i].minute+now.minute)>60){
expect[i].hour=(expect[i].hour+1)%24;
expect[i].minute=(need[i].minute+now.minute)%60;
}
else expect[i].minute=(need[i].minute+now.minute)%60;
printf("%d:%d\n",expect[i].hour,expect[i].minute);
}
return 0;
}
结构体指针的写法
结构体指针指向一般结构体变量:
struct student{
char name[10];
char sex;
int age;
};
int main(){
struct student stu1={"wm",'m',21};
struct student *p=stu1;
//初始化:法二
//struct student *p; p=stu1;
printf("姓名:%s\n性别:%c\n年龄:%d\n",p->name,p->sex,p->age); //结构体指针的输出
}
-
注意事项1:关于p++和++p:
int num=(p++)->num; //这时,p作为结构体指针,假设p指向了结构体1,那么num=结构体1.num,这个式子执行完成后,p就指 向结构体2 int num=(++p)->num; //这个式子执行完成后,p指向结构体2,num=结构体2.num //总结:无论如何,p++看作两行num=(p)->num;p=p+1;而++p无论如何也看做两行:p=p+1;num=(p)->num;
-
注意事项2:结构体指针的传递:
viod print(struct student *p){ //输出结构体变量的函数 printf("姓名:%s\n性别:%c\n年龄:%d\n",p->name,p->sex,p->age); } struct student *p=stu1; print(p); //注意传递指针的写法
基础延伸:链表的定义和书写
-
定义:
typedef struct node{ int num; struct node *next; }node_t,*pnode;//node_t是struct node的别名,而*pnode是struct node*的别名 //类似于typedef int x;之后就可以直接用x a;来替代int a; int main(){ pnode phead=NULL,ptail=NULL; //头指针和尾指针初始化 }