结构体
1、结构体类型的声明
结构体是一些值的集合,这些值称为成员变量,结果的每个成员可以是不同类型的变量
结构体的声明
struct tag
{
member-list
}variable-list;
例如:
#include <stdio.h>
#include <stdlib.h>
typedef struct Student
{
char name[20];//姓名
int age;//年龄
char sex[2];//性别
char id[20];//学号
}Student;
int main()
{
system("pause");
return 0;
}
结构体成员的类型:
结构体成员可以死hi标量,数组,指针,或者其他结构体等.
2、结构体变量的定义和初始化
#include <stdio.h>
#include <stdlib.h>
struct Point
{
int x;
int y;
}p1;//声明类型的同时定义变量p1
struct Point p2;//定义结构体变量p2
struct Point p3 = { 2, 3 };//定义今结构体变量p3并赋值
struct Stu
{
char name[20];
int age;
};
struct Stu s = { "zhangsan", 20 };
struct Node
{
int data;
struct Point p;
struct Node* next;
}n1 = { 10, { 4, 5 }, NULL };//结构体嵌套初识化
struct Node n2 = { 20, { 5, 6 }, NULL };
int main()
{
system("pause");
return 0;
}
3、结构体成员访问
结构体通过点操作符来访问成员
#include <stdio.h>
#include <stdlib.h>
//结构体访问通过.操作符实现
struct Stu
{
char name[20];
int age;
};
void Print(struct Stu *ps)
{
printf("name = %s age = %d", (*ps).name, (*ps).age);
}
int main()
{
struct Stu s = { "zhangsan", 20 };
Print(&s);
system("pause");
return 0;
}
4、结构体传参
由于函数在传参的时候需要进行压栈操作,如果结构体过大,栈的开销过大,会导致性能下降的问题
因此结构体传参要传结构体地址
#include <stdio.h>
#include <stdlib.h>
struct Student1
{
int data[1000];
int num;
};
struct Student1 s1 = { { 1, 2, 3, 4 }, 1000 };
//结构体传参
void Print1(struct Student1 s)
{
printf("%d\n", s.num);
}
//结构体地址传参
void Print2(struct Student1 *ps)
{
printf("%d\n", ps->num);
}
int main()
{
Print1(s1);
Print2(&s1);
system("pause");
return 0;
}