catalogue
2. Self reference of structure
3. Definition and initialization of structure variables
4. Structure member access (. And - > use)
Modify the default number of alignments
Structure foundation
1. Structure declaration
struct tag //Structure type name { member-list; //Member variables (list) }variable-list;//Variable list
Take a chestnut
struct stu { char name[20]; char sex[5]; int age; };
The above is the structure type. With the type, we can create the structure variable
struct stu { char name[20]; char sex[5]; int age; }s2,s3;//global variable struct stu s5;//global variable int main() { struct stu s1;//local variable return 0; }
struct { int a; char c; double d; }sa;//Note that variables can only be defined here (anonymous structure variables)
2. Self reference of structure
struct Node { int data; struct Node* next; };
Note that the structure cannot nest itself. To use it, please use the pointer (no dolls)
typedef struct Node { int data; struct Node* next; }Node;
When renaming a structure with typedef, the modified name cannot be used internally, but the name before renaming should be used
3. Definition and initialization of structure variables
struct stu { char name[20]; char sex[5]; int age; }; struct Data { struct stu s; char c; double b; }; int main() { struct Data sd = { {"lisi","nan",20},'a','3.14' }; }
4. Structure member access (. And - > use)
Structure memory alignment
struct stu { int a; char c; double d; }; int main() { printf("%d", sizeof(struct stu));//What is the size of the structure? return 0; }
We can calculate that the size of int is 4, the size of char is 1, and the size of double is 8, that is, 4 + 1 + 8 = 13. Is the result right? Let's verify it
You can see that the result is 16. Why?
OK, let's talk about why it's different from what we expected. Before that, let's learn about a library function offsetof
offsetof is the offset of the calculated structure member from the starting position
Structure alignment rules
1. Platform reason (migration reason):
Modify the default number of alignments
You need to use #pragma pack() to modify the default alignment number #
Baidu interview questions
#define OFFSETOF(s_name,n_name) (int)&(((s_name*)0)->n_name) struct stu { int a; char c; double d; }; int main() { printf("%d\n", OFFSETOF(struct stu, a));//0 printf("%d\n", OFFSETOF(struct stu, c));//4 printf("%d\n", OFFSETOF(struct stu, d));//8 return 0; }
Let's explain that we forcibly convert 0 to structure pointer - > member address is the offset, but if the type is structure type, we still need to forcibly convert it to integer
//#define OFFSETOF(s_name,n_name) (int)&(((s_name*)0)->n_name) // (int)&(((struct s*)0)->a)
The above is the summary of the structure. If you think it's helpful, just praise it