提示:以下是本篇文章正文内容,下面案例可供参考
一、结构体类型声明
代码如下(示例):
struct 是结构体关键字,Stu 是结构体标签。struct Stu是结构体类型
typedef类型重命名,声明时不需要在加struct关键字。
struct Stu
{
char name[20];
short age;
char tel[20];
} s1, s2, s3; //s1,s2,s3是全局结构体变量
typedef struct Stu1
{
char name[20];
short age;
char tel[20];
} Stu1;
int main()
{
struct Stu s1;
Stu1 s2;
return 0;
}
二、结构体初始化
代码如下(示例):
#include <stdio.h>
struct Book
{
char title[20];
};
typedef struct Stu
{
char name[20];
short age;
char *tel;
struct Book b;
} Stu;
int main()
{
char tel[] = "12312313";
struct Stu s1 = {"111", 2, tel, {"C++"}};
Stu s2 = {"222", 3, tel, {"C"}};
printf("%s\n", s1.name);
printf("%s\n", s2.name);
printf("%s\n", s1.tel);
printf("%s\n", s1.b.title);
printf("%s\n", s2.b.title);
}
三、结构体传参和成员访问
函数传参的时候,参数需要压栈,如果传递一个结构体对象的时候,结构体过大,参数压栈的系统开销比较大,会导致性能下降,所以条件允许的情况下传指针会更好。
代码如下(示例):
#include <stdio.h>
typedef struct Stu
{
char name[20];
short age;
char tel[20];
} Stu;
void Print(Stu stu)
{
printf("%s\n", stu.name);
printf("%d\n", stu.age);
printf("%s\n", stu.tel);
}
void Print2(Stu* stu)
{
printf("%s\n", stu -> name);
printf("%d\n", stu -> age);
printf("%s\n", stu -> tel);
}
int main()
{
Stu stu = {"123", 2, "123123123"};
Print(stu);
Print2(&stu);
}
总结
本章完。