36.结构体
结构体
1.struct是关键字
2.struct Student合起来才是结构体类型
3.结构体内部定义的变量不能直接赋值
4.结构体制是一个类型,没有定义变量之前,是没有分配空间,就不能赋值
#include<stdio.h>
#include<string.h>
struct Student{
int age;
char name[50];
int score;
};
int main()
{
struct Student stu;
stu.age = 19;
//stu.name = "Mike";//这样是错误的,因为name是数组名,数组名是常量,不可以修改
strcpy(stu.name, "Mike");
stu.score = 30;
//1.结构体变量的初始化,和数组一样,要使用大括号
//2.只有定义后才能初始化
struct Student tmp = {18, "mike", 59
};
//如果是指针,指正有合法指向,才能操作结构体成员
struct Student *p;
p = &tmp;
p->age = 18;
strcpy(p->name, "mike");
p->score = 59;
//任何结构体变量都可以用. 或者->操作成员
(&tmp) -> age = 18;
(*p).age = 18;
}
struct people
{
int age;
char name[50];
int score;
}s1 = {18, "mike", 59}, s2;
struct
{
int age;
char name[50];
int score;
}s3, s4;
结构体数组
#inlucde<stdio.h>
#inlucde<string.h>
//结构体数组
struct Student
{
int age;
char name[50];
int score;
}
int main(){
struct Student a[5]; //结构体数组
a[0].age = 18;
strcpy(a[0].name, "mike");
a[0].score = 59;
(a + 1) -> age = 19;
strpcy((a + 1)->name, "jiang");
(a + 1) -> score = 69;
(*(a + 2)).age = 20;
strcpy((*(a + 2)).name, "lily");
(*(a + 2)).score = 79;
struct Student *p = a;
p = &a[0];
p[3].age = 21;
p[3].score = 49;
strcpy(p[3].name, "xiaoming");
(p + 4) ->age = 22;
strcpy((p + 4)->name, "xiaojiang");
(p + 4)->score = 88;
int i = 0;
int n = sizeof(a)/sizeof(a[0]);
for(i = 0; i < n; i++)
{
printf("%d, %s, %d", a[i].age, a[i].name, a[i].score);
}
}
结构体的嵌套
#include<stdio.h>
struct Student
{
struct info;
int score;
};
struct info{
int age;
char name[50];
};
int main()
{
struct Student s;
s.info.age = 18;
strcpy(s.info.name, "mike");
s.score = 59;
struct Student *p = &s;
p->info.age = 18;
strcpy(p->info.name, "mike");
p->score = 59;
struct Student tmp = {18, "mike", 59};
printf("%d, %s, %d", tmp.info.age, tmp.info.name, tmp.score);
}