Article directory
-
- 1. What is a structure?
- 2. Definition of structure
- 3. Definition of structure variables
- 4. Initialization of structure variables
- 5. Assignment of structure variables
- 6. Reference members in structure variables
- 7. Parameter passing problem of structure variables
- 8. Problems caused by transmission addresses
- 9. Dynamic structure array
1. What is a structure?
In order to better simulate reality, various basic data types need to be combined to form a new composite data type. We call thiscustom data type< /span> is called a structure. A structure is a new composite data type formed by combining various basic data types according to actual needs.
2. Definition of structure
There are three ways to define a structure. Here we only use the most common and commonly used way, that is:
struct 结构体名
{
成员列表;
}; // 注意这里的分号不能省略
for example:
struct Student
{
int age;
float score;
char gender;
};
3. Definition of structure variables
The structure is the same as the basic data type we often use. It is also a data type, so we can use this data type to define its corresponding variables. We call variables defined with the structure type < /span>. The way to define structure variables is as follows:Structure variable
#include <stdio.h>
struct Student // 定义结构体
{
int age;
float score;
char gender;
};
int main()
{
struct Student stu; // 定义结构体变量
return 0;
}
4. Initialization of structure variables
#include <stdio.h>
struct Student // 定义结构体
{
int age;
float score;
char gender;
};
int main()
{
struct Student stu = {
15, 66.5, 'M' }; // 初始化结构体变量
return 0;
}
5. Assignment of structure variables
After defining the structure variable, we can assign values to its members, but unlike initialization, we need to assign each member of the structure variable through 结构体变量名.成员名
Assign values individually. The code is as follows
#include <stdio.h>
struct Student // 定义结构体
{
int age;
float score;
char gender;
};
int main()
{
struct Student stu; // 定义结构体变量
stu.age = 15; // 对结构体变量中的age成员赋值
stu.score = 66.5; // 对结构体变量中的score成员赋值
stu.gender = 'M'; // 对结构体变量中的gender成员赋值
return 0;
}
6. Reference members in structure variables
method 1:
结构体变量名.成员名
#include <stdio.h>
struct Student // 定义结构体
{
int age;
float score;
char gender;
};
int