目录
结构体类型的声明
结构是一些值的集合,这些值称为成员变量。结构的每个成员可以是不同类型的变量。
声明:
struct tag
{
member - list;
} variable - list;
struct stu
{
char name[20];
int age;
char sex[10];
float score;
}st1;
结构体成员的类型:标量,数组,指针,结构体
结构体初始化
1.初始化:
#include <stdio.h>
struct stu//定义一个结构体变量
{
char name[20];
int age;
char sex[10];
float score;
}stu2 = {"lisi",19,"male",78.4},stu3 = { "wangwu",20,"female",78.8 };//处世化结构变量,全局
struct stu stu4 = { "zhaoliu",21,"male",95.2 };
int main()
{
struct stu stu1 = { "zhangsan",18,"female",98.9 };//初始化结构体变量,局部
printf("%s %d %s %.1f\n", stu1.name, stu1.age, stu1.sex, stu1.score);
printf("%s %d %s %.1f\n", stu2.name, stu2.age, stu2.sex, stu2.score);
printf("%s %d %s %.1f\n", stu3.name, stu3.age, stu3.sex, stu3.score);
printf("%s %d %s %.1f\n", stu4.name, stu4.age, stu4.sex, stu4.score);
return 0;
}
2.结构体可以 嵌套初始化:
#include <stdio.h>
struct s
{
int a;
char b;
double c;
};
struct stu
{
char name[20];
int age;
char sex[10];
double score;
struct s ss;
}stu2 = { "lisi",19,"male",92.22,{24,'b',24.21} };
struct stu stu3 = { "wangwu",20,"female",93.22,{25,'c',25.21} };
int main()
{
struct stu stu1 = { "zhangsan",18,"female",91.22,{23,'a',23.21} };
printf("%s %d %s %.2lf %d %c %.2lf\n", stu1.name, stu1.age, stu1.sex, stu1.score, stu1.ss.a, stu1.ss.b, stu1.ss.c);
printf("%s %d %s %.2lf %d %c %.2lf\n", stu2.name, stu2.age, stu2.sex, stu2.score, stu2.ss.a, stu2.ss.b, stu2.ss.c);
printf("%s %d %s %.2lf %d %c %.2lf\n", stu3.name, stu3.age, stu3.sex, stu3.score, stu3.ss.a, stu3.ss.b, stu3.ss.c);
return 0;
}
结构体成员访问
三种访问方式
#include <stdio.h>
struct stu
{
char name[20];
int age;
char sex[20];
double score;
}stu1 = { "zhangsan",18,"female",98.22 };
int main()
{
struct stu* p = &stu1;
printf("%s %d %s %.2f\n", stu1.name, stu1.age, stu1.sex, stu1.score);
printf("%s %d %s %.2f\n", (*p).name, (*p).age, (*p).sex, (*p).score);
printf("%s %d %s %.2f\n", p->name, p->age, p->sex, p->score);
return 0;
}
结构体传参
利用函数将结构体打印出来;2种方式,选择传址调用较好,因为传址调用时,在堆栈区中开辟的空间小。而传值调用时,在堆栈中开辟的内存较大,会导致压栈,内存溢出;
#include <stdio.h>
struct S
{
int arr[1000];
float f;
char ch[100];
};
void print(struct S tmp)
{
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d ", tmp.arr[i]);//打印结构体成员arr中前10个元素
}
printf("\n");
printf("%f\n", tmp.f);
printf("%s\n", tmp.ch);
}
int main()
{
struct S s = { {1,2,3,4,5,6,7,8,9,10}, 5.5f, "hello world" };
print(s);//将结构体变量传给函数,传值调用
return 0;
}
#include <stdio.h>
struct stu
{
int arr[1000];
float f;
char ch[20];
}a = { {1,2,3,4,5,6,7,8,9,10},3.14,"hello world"};
void print(struct stu* a)
{
for (int i = 0; i < 10; i++)
{
printf("%d ", a->arr[i]);
}
printf("\n");
printf("%.2f\n", a->f);
printf("%s\n", a->ch);
}
int main()
{
print(&a);//传址调用
return 0;
}
#include <stdio.h>
struct stu
{
int arr[1000];
float f;
char ch[20];
}a = { {1,2,3,4,5,6,7,8,9,10},3.14,"hello world" };
void print(struct stu* a)
{
for (int i = 0; i < 10; i++)
{
printf("%d ", (*a).arr[i]);
}
printf("\n");
printf("%.2f\n", (*a).f);
printf("%s\n", (*a).ch);
}
int main()
{
print(&a);//传址调用
return 0;
}