ToB企服应用市场:ToB评测及商务社交产业平台

标题: C语言加强 [打印本页]

作者: tsx81429    时间: 2024-5-19 06:10
标题: C语言加强
变量、指针和关键字

两个口诀:

指针

变量

extern 关键字

留意 extern int b 不能被赋值!!!这个是声明,表示 b 是什么
不建议使用 extern,可以使用函数来进行值通报
static 关键字

volatile 关键字

布局体

布局体对齐

为什么会有内存对齐

对齐规则

这里的对齐参数取每个变量自身对齐参数和系统默认参数#pragma pack(n)(一般为 8)中较小的谁人
这里的对齐参数取布局体中全部变量对齐参数的最大值和系统默认参数对比取较小的

图解
  1. | char |     |     |     | 4字节
  2. | int  | int | int | int | 4字节
  3. | short|short|     |     | 4字节
复制代码
  1. | char |     |short|short| 4字节
  2. | int  | int | int | int | 4字节
复制代码
实例

  1. typedef struct
  2. {
  3.     char c;
  4.     short d;
  5.     static int a;
  6. }A;
复制代码
  1. | char |     | 2字节
  2. | short|short| 2字节
复制代码
易错点:对于布局体中的 static int a ,静态数据成员存放位置与布局体实例的存储地点无关,不算在内里
只有 C++ 布局体中才有 static,C 语言中不允许有

  1. typedef struct
  2. {
  3.     double b;
  4.     int c;
  5. }D;
  6.    
  7. typedef struct
  8. {
  9.     bool a;   // bool为1字节
  10.     D d;
  11.     double b;
  12.     int c;
  13. }E;
复制代码
  1. |bool|-----------------------------------| 8字节
  2. |--------------------D-------------------| 8字节
  3. |--------------------D-------------------| 8字节
  4. |------------------double----------------| 8字节
  5. |---------int--------|-------------------| 8字节
复制代码
易错点:D 与默认的 8 比,8 小,取 8 为对齐参数
变量赋值

  1. p = &a;
  2. *p = 123;  // 将a的值变为123
复制代码
  1. pt = &A;
  2. pt->age = 20;  // pt为指针,取成员用"->",结构体用"."
  3. *pt = A2;     // 将A变成A2的值
复制代码
布局体指针
  1. typedef struct student{
  2.     char *name;
  3.     int age;
  4.     struct student *classmate;   // 结构体中只能用指针,长度为4个字节(链表)
  5. }student, *pstudent;
  6. student zhangsan = {"zhangshan", 10, NULL};
  7. student lili = {"lili", 20, NULL};
  8. zhangsan.classmate = &lili;  // 构成链表
  9. name = zhangsan.classmate->name;   // zhangsan为结构体,用"."取值,classmate为指针,用"->"取值
复制代码
函数指针
  1. void (*add){};  // 函数指针,变量,占4字节
  2. typedef struct student{
  3.     char *name;
  4.     int age;
  5.     void (*good_work)(void);  // 函数指针
  6.     struct student *classmate;
  7. }student, *pstudent;
  8. // add为函数指针,也可以写成&add
  9. // 函数指针是变量,所以可以赋值为地址,函数不是变量,只能被调用
  10. student ss[2] = {{"zhangshan", 10, add, NULL}, {"lili", 20, add, NULL}};  // 结构体数组
  11. ss[1].good_work();   // 结构体调用函数指针,用"."
  12. pstudent get(void){
  13.     int type = 1;
  14.     return &ss[type];  // 返回结构体指针
  15. }  // 应尽量避免使用全局变量,可以将变量封装在函数里
  16. pstudent a;
  17. a = get();
  18. a->good_work();   //这里a为结构体指针,用"->"
复制代码
全局变量与局部变量

参考资料

https://www.bilibili.com/video/BV1VM4y137Pm/?spm_id_from=333.999.0.0
https://blog.csdn.net/qq_41068271/article/details/83446623?spm=1001.2014.3001.5502

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4