当前位置:网站首页>Part I - Fundamentals of C language_ 9. Composite type (custom type)
Part I - Fundamentals of C language_ 9. Composite type (custom type)
2022-07-21 18:55:00 【qq_ forty-three million two hundred and five thousand two hundr】
9.1 Structure
9.1.1 summary
Array : Describes an ordered set of data of the same type , Used to process a large number of data operations of the same type .
Sometimes we need to combine different types of data into an organic whole , Such as : A student has a student number / full name / Gender / Age / Address and other properties . Obviously, it is tedious to define the above variables alone , Data is not easy to manage .
C Language gives another type of construction data —— Structure .
9.1.2 Structure variable definition and initialization
How to define structure variables :
- First declare the structure type and then define the variable name
- Define variables while declaring types
- Directly define structure type variables ( No type name )
Structure type and structure variable relationship :
4. Type of structure : A structure type was specified , It's equivalent to a model , But there is no specific data , The system doesn't allocate real memory units to it either .
5. Structural variable : The system depends on the structure type ( Internal member status ) Allocate space for it .
//1. Define the type first , Redefining variables ( Commonly used )
struct stu
{
char name[50];
int age;
};
struct stu s1 = { "mike", 18 };
//2. Define types and variables
struct stu2
{
char name[50];
int age;
}s2 = { "lily", 22 };
//3. One time definition
struct
{
char name[50];
int age;
}s3 = { "yuri", 25 };
9.1.3 Use of structural members
#include<stdio.h>
#include<string.h>
// Definition of structure type
struct stu
{
char name[50];
int age;
};
int main()
{
struct stu s1;
//1. If it's a normal variable , Manipulate structure members through point operators
strcpy(s1.name, "abc");
s1.age = 18;
printf("s1.name = %s, s1.age = %d\n", s1.name, s1.age);
//2. If it's a pointer variable , adopt -> Operation structure member
strcpy((&s1)->name, "test");
(&s1)->age = 22;
printf("(&s1)->name = %s, (&s1)->age = %d\n", (&s1)->name, (&s1)->age);
return 0;
}
9.1.4 Array of structs
#include <stdio.h>
// Count the student's scores
struct stu
{
int num;
char name[20];
char sex;
float score;
};
int main()
{
// Define a containing 5 Structure array of elements and initialize it
struct stu boy[5] =
{
{ 101, "Li ping", 'M', 45 },
{ 102, "Zhang ping", 'M', 62.5 },
{ 103, "He fang", 'F', 92.5 },
{ 104, "Cheng ling", 'F', 87 },
{ 105, "Wang ming", 'M', 58 }
};
int i = 0;
int c = 0;
float ave, s = 0;
for (i = 0; i < 5; i++)
{
s += boy[i].score; // Calculate the total score
if (boy[i].score < 60)
{
c += 1; // Count the scores of unqualified people
}
}
printf("s=%f\n", s); // Print total score
ave = s / 5; // Calculate the average score
printf("average=%f\ncount=%d\n", ave, c); // Print the average score and the number of failed
for (i = 0; i < 5; i++)
{
printf(" name=%s, score=%f\n", boy[i].name, boy[i].score);
}
return 0;
}
9.1.5 Structure sleeve structure
#include <stdio.h>
struct person
{
char name[20];
char sex;
};
struct stu
{
int id;
struct person info;
};
int main()
{
struct stu s[2] = { 1, "lily", 'F', 2, "yuri", 'M' };
int i = 0;
for (i = 0; i < 2; i++)
{
printf("id = %d\tinfo.name=%s\tinfo.sex=%c\n", s[i].id, s[i].info.name,
s[i].info.sex);
}
return 0;
}
9.1.6 Structure assignment
#include<stdio.h>
#include<string.h>
// Definition of structure type
struct stu
{
char name[50];
int age;
};
int main()
{
struct stu s1;
strcpy(s1.name, "abc");
s1.age = 18;
printf("s1.name = %s, s1.age = %d\n", s1.name, s1.age);
// Two structural variables of the same type , You can assign values to each other
struct stu s2 = s1;
printf("s2.name = %s, s2.age = %d\n", s2.name, s2.age);
return 0;
}
9.1.7 Structures and pointers
1) Pointer to a normal structure variable
#include<stdio.h>
// Definition of structure type
struct stu
{
char name[50];
int age;
};
int main()
{
struct stu s1 = { "lily", 18 };
// If it's a pointer variable , adopt -> Operation structure member
struct stu *p = &s1;
printf("p->name = %s, p->age=%d\n", p->name, p->age);
return 0;
}
2) Heap structure variable
#include<stdio.h>
#include <string.h>
#include <stdlib.h>
// Definition of structure type
struct stu
{
char name[50];
int age;
};
int main()
{
struct stu *p = NULL;
p = (struct stu *)malloc(sizeof(struct stu));
// If it's a pointer variable , adopt -> Operation structure member
strcpy(p->name, "test");
p->age = 22;
printf("p->name = %s, p->age=%d\n", p->name, p->age);
free(p);
p = NULL;
return 0;
}
3) Structure set primary pointer
#include<stdio.h>
#include <string.h>
#include <stdlib.h>
// Definition of structure type
struct stu
{
char *name; // First level pointer
int age;
};
int main()
{
struct stu *p = NULL;
p = (struct stu *)malloc(sizeof(struct stu));
p->name = malloc(strlen("test") + 1);
strcpy(p->name, "test");
p->age = 22;
printf("p->name = %s, p->age=%d\n", p->name, p->age);
if (p->name != NULL)
{
free(p->name);
p->name = NULL;
}
if (p != NULL)
{
free(p);
p = NULL;
}
return 0;
}
9.1.8 Structure is used as function parameter
1) Structure ordinary variables as function parameters
#include<stdio.h>
#include <string.h>
// Definition of structure type
struct stu
{
char name[50];
int age;
};
// Function parameters are structural ordinary variables
void set_stu(struct stu tmp)
{
strcpy(tmp.name, "mike");
tmp.age = 18;
printf("tmp.name = %s, tmp.age = %d\n", tmp.name, tmp.age);
}
int main()
{
struct stu s = { "C Language ",0 };
set_stu(s); // Value passed
printf("s.name = %s, s.age = %d\n", s.name, s.age);
return 0;
}
Output results
tmp.name = mike, tmp.age = 18
s.name = C Language , s.age = 0
2) Structure pointer variables as function parameters
#include<stdio.h>
#include <string.h>
// Definition of structure type
struct stu
{
char name[50];
int age;
};
// The function parameter is the structure pointer variable
void set_stu_pro(struct stu* tmp)
{
strcpy(tmp->name, "mike");
tmp->age = 18;
printf("tmp.name = %s, tmp.age = %d\n", tmp->name, tmp->age);
}
int main()
{
struct stu s = { "C Language ",0 };
set_stu_pro(&s); // Address delivery
printf("s.name = %s, s.age = %d\n", s.name, s.age);
return 0;
}
tmp.name = mike, tmp.age = 18
s.name = mike, s.age = 18
3) Structure array name as function parameter
#include<stdio.h>
// Definition of structure type
struct stu
{
char name[50];
int age;
};
void set_stu_pro(struct stu *tmp, int n)
{
int i = 0;
for (i = 0; i < n; i++)
{
sprintf(tmp->name, "name%d", i);
tmp->age = 20 + i;
tmp++;
}
}
int main()
{
struct stu s[3] = { 0 };
int i = 0;
int n = sizeof(s) / sizeof(s[0]);
set_stu_pro(s, n); // Array name passing
for (i = 0; i < n; i++)
{
printf("%s, %d\n", s[i].name, s[i].age);
}
return 0;
}
name0, 20
name1, 21
name2, 22
4)const Modifier structure pointer parameter variable
// Definition of structure type
struct stu
{
char name[50];
int age;
};
void fun1(struct stu * const p)
{
//p = NULL; //err, The direction cannot be changed
p->age = 10; //ok
}
void fun2(const struct stu * p)
{
p = NULL; //ok
//p->age = 10; //err, The content cannot be changed
}
void fun3(const struct stu * const p)
{
//p = NULL; //err
//p->age = 10; //err
}
9.2 Consortium
- union union It is a type that can store different types of data in the same storage space ;
- The memory length occupied by the consortium is equal to multiple of the length of its longest member ;
- The same memory segment can be used to store several different types of members , But there's only one thing that works in every instant ;
- The active member in the consortium variable is the last stored member , After saving a new member, the value of the original member will be overwritten ;
- The address of the consortium variable is the same as that of its members .
#include <stdio.h>
// A consortium is also called a consortium
union Test
{
unsigned char a;
unsigned int b;
unsigned short c;
};
int main()
{
// Define common body variables
union Test tmp;
//1、 The first address of all members is the same
printf("%p, %p, %p\n", &(tmp.a), &(tmp.b), &(tmp.c));
//2、 The size of the community is the size of the largest member type
printf("%lu\n", sizeof(union Test));
//3、 A member assignment , Will affect other members
// Lower address , Put high address
tmp.b = 0x44332211;
printf("%x\n", tmp.a); //11
printf("%x\n", tmp.c); //2211
return 0;
}
9.3 enumeration
enumeration : List the values of variables one by one , The value of a variable is limited to the values listed .
Enumeration type definition
enum Enum name
{
Enumeration table
};
- All available values should be listed in the enumeration value table , Also known as enumeration elements .
- Enumeration values are constants , You can't assign a value to it with an assignment statement in a program .
- For example, the element itself is defined by the system as a value representing the sequence number from 0 The starting order is defined as 0,1,2 …
#include <stdio.h>
enum weekday
{
sun = 2, mon, tue, wed, thu, fri, sat
} ;
enum bool
{
flase, true
};
int main()
{
enum weekday a, b, c;
a = sun;
b = mon;
c = tue;
printf("%d,%d,%d\n", a, b, c);
enum bool flag;
flag = true;
if (flag == 1)
{
printf("flag It's true \n");
}
return 0;
}
9.4 typedef
typedef by C Keywords of language , The function is for a data type ( Basic type or custom data type ) Define a new name , Cannot create new type .
- And #define Different ,typedef Data types only , Instead of an expression or a specific value
- #define Occurs during preprocessing ,typedef It happens in the compilation phase
#include <stdio.h>
typedef int INT;
typedef char BYTE;
typedef BYTE T_BYTE;
typedef unsigned char UBYTE;
typedef struct type
{
UBYTE a;
INT b;
T_BYTE c;
}TYPE, *PTYPE;
int main()
{
TYPE t;
t.a = 254;
t.b = 10;
t.c = 'c';
PTYPE p = &t;
printf("%u, %d, %c\n", p->a, p->b, p->c);
return 0;
}
254, 10, c
边栏推荐
- 程序初学者推荐学哪种编程语言比较好?
- SOHO @ L2TP/IPsec Issue
- [translation] improve stability and reliability with kubernetes + helm + flux!
- OSPF基础
- How to extract the specified column from the database of multiple imputation as a new variable
- C语言类型转换
- Golang collection: custom types and method sets
- 嵌入式学习:Cortex-M系列芯片介绍
- 最新开源!基于LiDAR的位置识别网络OverlapTransformer,RAL/IROS 2022
- Can messages in CAPL: declaration, sending and receiving
猜你喜欢
全新红包封面平台可搭建分站独立后台的源码
Pagination universelle (encapsulation du Code de pagination)
Involution: Inverting the Inherence of Convolution for Visual Recognition(CVPR2021)
bryntum gantt 5.0.6
Pytorch uses nn Unfold realizes convolution operation again
Zhongang Mining: four trends of fluorite industry development
机器学习-单变量线性回归
Test the mock data method of knowing and knowing
2022 dsctf first digital space security attack and defense competition
Qt development skills and three problems
随机推荐
Ctfhub information disclosure
数字孪生技术打造智慧矿山可视化解决方案
RENIX_ IPv6 automatic configuration -- practical operation of network tester
This is the package I am most familiar with JSON?
Leetcode:06zigzag transformation
C language -- 24 Gobang
Splicing of SRC variables in wechat applet pictures
微信小程序 图片src变量拼接问题
Control in canoe panel: switch/indicator
深度优先与广度优先的思想
读秀数据库的用法+全国图书馆参考咨询联盟
How much has changed from new retail to community group purchase?
Introduction to C language --- operators
Face recognition attendance system based on jsp/servlet
The domestic epidemic is repeated. How can offline physical stores be transformed to break through the dilemma?
Kubernetes技术与架构(五)
众昂矿业:萤石行业发展四大趋势
一种非极大值抑制(non_max_suppression, nms)的代码实现方式
HCIP第四天
Security video monitoring platform easycvr database fields cannot be updated, how to optimize?