C语言结构体的用法
结构体是一种复杂的数据类型,在C语言中经常使用。结构体的定义、使用和操作都是C语言程序设计中的重要知识点。
一、 结构体类型定义
结构体类型定义是指定义一个结构体的组织形式,但不分配内存。结构体类型定义的格式为:
```c
struct 结构体名 {
类型标识符 成员名;
类型标识符 成员名;
…………….
};
```
例如:
```c
struct student {
int num;
char name[20];
char sex;
int age;
float score;
char addr[30];
};
```
结构体类型定义只是描述结构的组织形式,不会分配内存。
二、 结构体变量的定义
结构体变量的定义是指定义一个结构体变量,并分配内存。结构体变量的定义格式为:
```c
struct 结构体名 变量名;
```
例如:
```c
struct student stu1, stu2;
```
结构体变量可以嵌套结构体成员,例如:
```c
struct date {
int month;
int day;
int year;
};
struct student {
int num;
char name[20];
struct date birthday;
} stu;
```
三、 结构体变量的引用
结构体变量不能整体引用,只能引用变量成员。引用方式为:
```c
结构体变量名 . 成员名
```
例如:
```c
struct student stu1, stu2;
stu1.num = 10;
stu1.score = 85.5;
stu1.score += stu2.score;
stu1.age++;
```
四、 结构体变量的初始化
结构体变量可以在定义时初始化,例如:
```c
struct student stu1 = {1, "Li", 'M', 20, 85.5, "Beijing"};
```
五、 结构体数组
结构体数组是指一个数组中的每个元素都是一个结构体变量。例如:
```c
struct student stu[5];
```
六、 结构体和指针
结构体变量可以作为指针的对象,例如:
```c
struct student *pstu;
```
七、 结构体与函数
结构体变量可以作为函数的参数,例如:
```c
void print_student(struct student stu) {
printf("Name: %s, Age: %d\n", stu.name, stu.age);
}
int main() {
struct student stu = {1, "Li", 'M', 20, 85.5, "Beijing"};
print_student(stu);
return 0;
}
```
八、 链表
链表是一种特殊的结构体数组,链表中的每个元素都是一个结构体变量,并且每个元素都指向下一个元素。例如:
```c
struct node {
int data;
struct node *next;
};
```
结构体是C语言中的一个重要知识点,掌握结构体的定义、使用和操作是C语言程序设计的基础。