结构体
一、什么是结构体
struct 结构体名{
类型名1 成员名1;
类型名2 成员名2;
……
类型名n 成员名n;
};
struct Student {
char *name; // 姓名
int age; // 年龄
float height; // 身高
};
三、结构体变量的定义
struct Student {
char *name;
int age;
};
struct Student stu;
2.定义结构体类型的同时定义变量
struct Student {
char *name;
int age;
} stu;
struct {
char *name;
int age;
} stu;
1struct Student {
2 int age;
3 struct Student stu;
4 };
struct Date {
int year;
int month;
int day;
};
struct Student {
char *name;
struct Date birthday;
};
struct Student {
char *name;
int age;
};
struct Student stu;
struct Student {
char *name; // 姓名
int age; // 年龄
float height; // 身高
};
struct Student {
char *name;
int age;
};
struct Student stu = {“NJ", 27};
struct Student stu;
stu = {“NJ", 27};
结构体的使用
struct Student {
char *name;
int age;
};
struct Student stu;
// 访问stu的age成员
stu.age = 27;
struct Date {
int year;
int month;
int day;
};
struct Student {
char *name;
struct Date birthday;
};
struct Student stu;
stu.birthday.year = 1986;
stu.birthday.month = 9;
stu.birthday.day = 10;
struct Student {
char *name;
int age;
};
struct Student stu1 = {“NJ”, 27};
// 将stu1直接赋值给stu2
struct Student stu2 = stu1;
printf("age is %d", stu2.age);
struct Student {
char *name;
int age;
};
struct Student stu[5]; //定义1
struct Student {
char *name;
int age;
} stu[5]; //定义2
struct {
char *name;
int age;
} stu[5]; //定义3
struct {
char *name;
int age;
} stu[2] = { {”NJ", 27}, {"JJ", 30} };
#include <stdio.h>
2
3 // 定义一个结构体
4 struct Student {
5 int age;
6 };
7
8 void test(struct Student stu) {
9 printf("修改前的形参:%d \n", stu.age);
10 // 修改实参中的age
11 stu.age = 10;
12
13 printf("修改后的形参:%d \n", stu.age);
14 }
15
16 int main(int argc, const char * argv[]) {
17
18 struct Student stu = {30};
19 printf("修改前的实参:%d \n", stu.age);
20
21 // 调用test函数
22 test(stu);
23
24
25 printf("修改后的实参:%d \n", stu.age);
26 return 0;
27 }
#include <stdio.h>
2
3 int main(int argc, const char * argv[]) {
4 // 定义一个结构体类型
5 struct Student {
6 char *name;
7 int age;
8 };
9
10 // 定义一个结构体变量
11 struct Student stu = {“NJ", 27};
12
13 // 定义一个指向结构体的指针变量
14 struct Student *p;
15
16 // 指向结构体变量stu
17 p = &stu;
18
19 /*
20 这时候可以用3种方式访问结构体的成员
21 */
22 // 方式1:结构体变量名.成员名
23 printf("name=%s, age = %d \n", stu.name, stu.age);
24
25 // 方式2:(*指针变量名).成员名
26 printf("name=%s, age = %d \n", (*p).name, (*p).age);
27
28 // 方式3:指针变量名->成员名
29 printf("name=%s, age = %d \n", p->name, p->age);
30
31 return 0;
32 }