Defines the use of struct variables, struct Variables
(1) define struct types
1. A user-created data structure composed of different types of data is called a struct.
For example:
Struct Date
{Int month;
Int day;
Int year;
};
Struct Student
{Int num;
Char name [20];
Char sex;
Int age;
Struct Date birthday;
Char addr [20];
};
The members in the struct can belong to another struct type, for example, birthday in the preceding example.
This only creates a struct type and does not define variables, so the system does not allocate storage units to it.
(2) define struct type variables
(1) Declare the type before defining the variable
Struct Student student1, student2;
(2) Declare types and define variables at the same time
Struct Student {
Int num;
Char name [20];
.............
} Student1, student2;
(3) initialization and reference of struct Variables
Initialization example:
1 #include<stdio.h> 2 int main(){ 3 struct Student{ 4 long int num; 5 char name[20]; 6 char sex; 7 char addr[20]; 8 }a={1001,"Li",'M',"BeiJing"}; 9 printf("name:%s\naddress:%s\n",a.name,a.addr);10 }
Struct variables of the same type can be assigned values to each other, for example, student1 = student2.
Example:
1 # include <stdio. h> 2 int main () {3 struct student {4 int num; 5 char name [20]; 6} student1; 7 scanf ("% d % s", & student1.num, student1.name); 8 printf ("student ID: % d \ n name: % s \ n", student1.num, student1.name); 9}
Note: scanf has a value character when inputting num, but no value when inputting name. This is because the array name itself represents the address.