1, There are four definitions of structure types and structure variables:
1. Define type structure type first, and then structure variable
struct stu { int num; char *name; }; void test() { struct stu people; }
2. Define variables when defining structure type
struct stu { int num; char *name; }xiao_ming, xiao_hong;
3. Type of disposable structure
struct { int num; char *name; }xiao_ming, xiao_hong;
4. You can define variables multiple times by aliasing one-time structures.
struct { int num; char *name; }STU;
2, Initialization of structure variables:
1. Define variables as initialization
struct stu { int num; char *name; }; void test() { struct stu people = {10, "xiao_ming"}; }
2. Define variables and initialize at the same time when defining a structure
struct stu { int num; char *name; }xiao_ming = {10, "xiao_ming"}, xiao_hong = {20, "xiao_hong"};
3. Use memset to initialize the structure to 0
struct stu { int num; char *name; }; void test() { struct stu people; memset(&people, 0, sizeof(people)); }
4. Member by member assignment
struct stu { int num; char *name; }; void test() { struct stu people; people.num = 10; people.name = "xiao_ming"; }
3, Access to members:
- Structure variable name. Member variable name
- Structure address - > member variable name
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> #include<string.h> int main(int argc, char *argv[]) { struct stu tom = {10, "tom", 10.0f}; struct stu *p = &tom; printf("num = %d, name = %s, score = %f\n", p->num, p->name, p->score); printf("num = %d, name = %s, score = %f\n", (*p).num, (*p).name, (*p).score); printf("num = %d, name = %s, score = %f\n", tom.num, tom.name, tom.score); printf("num = %d, name = %s, score = %f\n", (&tom)->num, (&tom)->name, (&tom)->score); system("pause"); return 0; }
Note 1:
- Structure (object) members select the use point (variable name on the left).
- Pointer members choose to use the pointing operator (address on the left).
Note 2:
- The structure address is the same as the address of the first member variable. Unlike arrays, the variable name of a structure is not an address. You need to use the address character for the variable name.
- Structure address - > member variable name < = = > member variable name < = = > * member variable address.
- Just remember that the structure address can find the address of the member variable through - > (point operator), and directly operate the content corresponding to the address.