Struct in C Language
1 struct student2 {3 int id; 4 char name[10];5 6 };
Note: student is a custom data type, not a variable like int, char is a basic data type,
- Struct variable definition and reference:
1 struct student 2 {3 int id; 4 char name [10]; 5} mike, lily; // directly define two struct Variables
1 student mike = {123, {'M', 'I', 'k', 'E'}; // define the variable and initialize 2 mike. id = 20130000 + mike. id // use 3 for (int I = 0; mike. name [I]! = '\ 0'; I ++) 4 mike. name [I] = toupper (mike. name [I]); 5 cout <"ID:" <mike. id <"name:" <mike. name <endl ;//
- Storage of struct variables:
A struct variable occupies a continuous memory space.
- Struct variable assignment:
1 student mike = {123, {'M', 'I', 'k', 'E'}; 2 student lily; 3 lily = mike; // you can assign values directly, the corresponding variable is also assigned a value.
- Struct variables are used as function parameters.
The parameter is the same as the function parameter used for variable creation. When the parameter is directly passed as the parameter value, only one copy is copied, which is different from the parameter used for array name.
- Struct variable as the return value of the Function
A copy is also used to assign values.
student mike={123,{'m','i','k','e'}};student *ps = &mike; cout<<"ID: "<<(*ps).id<<"name: " <<(*ps).name<<endl;cout<<"ID:"<<ps->id<<"name: "<<ps->name<<endl;
1 struct student 2 {3 int id;4 char name[10];5 } stu[10];
- Summary: The features of struct data types are consistent with those of common data types.