C language structure

2022-08-06 09:32:33

前言

Today we will look at structs,We know that an array is a collection of elements of the same type,But in everyday life we ​​often have to write many different types of elements together,For example the title of a book、作者、价格、release date, etc.,This is where we need to use structs.

结构体的声明

结构体声明

``````struct tag
{

member - list;
}variable - list;
``````

``````struct Stu
{

char name[20];//名字
int age;//年龄
char sex[5];//性别
char id[20];//学号
}Stu;//分号不能丢
``````

结构体变量的定义和初始化

``````struct Point//这里struct Point是声明
{

int x;
int y;
}p1; //声明类型的同时定义变量p1,这里的p1是定义
struct Point p2; //定义结构体变量p2

struct Point p3 = {
5, 6};//初始化：定义变量的同时赋初值.这里5会赋值给x,6会赋值给y.

struct Stu //类型声明
{

char name[15];//名字
int age; //年龄
};
struct Stu s = {
"zhangsan", 20};//初始化

struct Node
{

int data;
struct Point p;//The above is nested herePoint结构体
struct Node* next;//结构体指针,这个后续会讲,多用于C语言的数据结构
}n1 = {
10, {
4,5}, NULL}; //结构体嵌套初始化
struct Node n2 = {
20, {
5, 6}, NULL};//结构体嵌套初始化
``````

结构体成员的访问

``````#include <stdio.h>
struct Point
{

int x;
int y;
}p1;//声明类型的同时定义变量p1,Don't forget the semicolon here
struct Point p2;//定义结构体变量p2
int main()
{

p1.x = 10;//.操作符
p1.y = 20;
printf("%d %d ", p1.x, p1.y);
return 0;
}
``````

Here you can see that the structure variable is assigned first,And print the structure variables are used.操作符.

``````#include <stdio.h>
#include <string.h>
struct Stu
{

char name[20];
int age;
};
struct Stu s;
int main()
{

strcpy(s.name, "zhangsan");//使用.访问name成员,Just pay attention to the use of assigning strings to structure variablesstrcpy函数
s.age = 20;//使用.访问age成员
printf("%s %d ", s.name, s.age);
return 0;
}
``````

There are other times when we use struct pointers,At this time, if we want to use the variables in the structure, we need to use other operators,以下为代码示例：

``````#include <stdio.h>
#include <string.h>
struct Stu
{

char name[20];
int age;
};
void print(struct Stu* ps)
{

printf("name = %s age = %d\n", (*ps).name, (*ps).age);
//使用结构体指针访问指向对象的成员
printf("name = %s age = %d\n", ps->name, ps->age);
}
int main()
{

struct Stu s = {
"zhangsan", 20 };
print(&s);//结构体地址传参
return 0;
}
``````

结构体传参

``````#include <stdio.h>
#include <string.h>
struct S
{

int data[1000];
int num;
};
struct S s = {
{
1,2,3,4}, 1000 };//结构体赋值
//Structure passed value parameters
void print1(struct S s)
{

printf("%d\n", s.num);
}
//结构体地址传参
void print2(struct S* ps)
{

printf("%d\n", ps->num);
}
int main()
{

print1(s); //传结构体
print2(&s); //传地址
return 0;
}
``````

As the above structure has five shapes元素, Assignment may be required when calling by value20字节的空间,And only when passing the address4个字节就可以（Because in a certain wayx86pointers in the programming environment4个字节）,So if you call by reference, it will greatly save memory space.

Looking forward to your last trip,如有错误,Welcome to private message or correct me in the comment section.