(c language) Getting to know the structure

Table of contents

1. Declaration of structure

1.1 Basic knowledge of structure

1.2 Declaration of structure 

1.3 Types of structure members 

1.4 Definition and initialization of structure variables 

2. Access and parameter transfer of structure members 


1. Declaration of structure

1.1 Basic knowledge of structure

A structure is a collection of values ​​called member variables. Each member of the structure can be a variable of a different type.

For example common: int char, long..... 

1.2 Declaration of structure 

struct tag
{
member-list;
}variable-list; 

give two examples

typedef struct Stu
{       char name[20];//name       int age;//age       char sex[5];//gender       char id[20];//student number }Stu;//remember the semicolon can not be lost




Declaration of structure type
//struct Stu
//{ // char name[20];//name // int age;//age // char sex[8];//sex // float score; //} s1, s2, s3; s1, s2, s3 are variables created by struct Stu type s1, s2, s3 are global variables






1.3 Types of structure members 

Members of structures can be scalars, arrays, pointers, or even other structures. 

1.4 Definition and initialization of structure variables 

edef type redefinition/renaming, that is, aliasing

//declaration of structure type
//typedef struct Stu
//{ // char name[20];//name // int age;//age // char sex[8];//sex // float score; // }Stu; // //int main() //{ // //s4, s5 are local variables // //struct Stu is the structure type, struct cannot be omitted casually // // struct Stu s4; // struct Stu s5; // Stu s6; // // return 0; //} // 

















2. Access and parameter transfer of structure members 

//. Structure variable. Structure member
//-> Structure pointer -> Structure member 

struct Point
{
	int x;
	int y;
}p1 = {10, 15};

struct S
{
	char c;
	struct Point sp;
	double d;
	char arr[20];
};

void print1(struct S s)
{
	printf("%c\n", s.c);
	printf("%d %d\n", s.sp.x, s.sp.y);
	printf("%lf\n", s.d);
	printf("%s\n", s.arr);
}
void print2(struct S* ps)
{
	printf("%c\n", ps->c);
	printf("%d %d\n", ps->sp.x, ps->sp.y);
	printf("%lf\n", ps->d);
	printf("%s\n", ps->arr);
}
int main()
{
	struct Point p = {100, 200};
	struct S ss = { 'w', {100,20}, 5.5, "hello"};
	//ss.c = 'b';
	//ss.sp.x = 1000;
	//ss.sp.y= 2000;
	//ss.d = 3.14;
	//strcpy(ss.arr, "world");//strcpy字符串拷贝
	print1(ss);//打印struct S类型的变量
	print2(&ss);//

	return 0;
}

When a function passes parameters, the parameters need to be pushed onto the stack. (I will talk about this part in a follow-up article).

If a structure object is passed, the structure is too large, and the system overhead of pushing the parameters to the stack is relatively large, which will lead to a
decrease in performance.

Guess you like

Origin blog.csdn.net/m0_63562631/article/details/126164422