基础

函数参数

值-结果参数:函数内部可以修改实参,修改后通过实参返回。通过指针模拟这一机制。

判断值-结果参数:

dict* dictCreate(dictType* type, void* privData);

dict* dictCreate(dictType* type, void** privData);

FILE* file; fopen_s(&file, "test.txt", "r"); 内部修改file指向

柔性数组,和普通指针声明有啥区别?

  • 柔性数组作为最后一个结构体成员,一次malloc时候连续挨着分配,避免两次分配碎片。
  • 柔性数组因此只能一次分配,后续不可扩展
  • sizeof 有柔性数组的结构体,会不计算该字段。比如{int id; char data[];}计算值为4
  • free 柔性数组只要一次。

static

声明全局变量,比如type,内部能携带static吗,比如属性函数为static?

A:即外部可以通过type->hash()调用,而hash为static在本文件,static表示在本文件直接调用

向前声明

向前声明 就是告诉编译器:“这个类型(结构体、类、函数)将来会定义,但你现在只需要知道它的名字。”

比如:db中需要redis中的rediscommand, 而redis中需要db中的redisDB,会报错找不到!

解决:后续使用struct 指针,并添加向前声明。

1
2
3
4
5
6
7
8
9
10
struct redisCommand;  // 向前声明 redisCommand

typedef void func(struct redisCmd * cmd)

typedef struct redisDb {
dict *dict; // 存储键值对
int id; // 数据库编号
struct redisCommand *cmd;
} redisDb;

函数指针、函数类型、typedef定义函数

函数指针

函数指针:指向函数的指针。

指针声明:

1
int (*funcPtr)(int, int);

指针赋值

funcPtr = add;

通过函数指针调用

funcPtr(1,2)

typedef 定义

  • 定义函数类型

    typedef int FuncType(int, int);

    FuncType add;

    这等价于声明了函数 int add(int, int);

  • 定义函数指针类型

    typedef int (*FuncPtr)(int, int);

    FuncPtr p = add; p指向一个函数,通过p(1,2)调用

    这等价于

    1
    2
    int (*ptr)(int,int) = add;
    ptr(1,2);

    !!所以可以存储指针变量。而函数类型只能存储函数名。

  • 联系

    typedef int func();这是函数类型, func*为函数指针类型。

    赋值都是通过函数名就可以。

其他

int (*listGetCompareMethod(list *list))(void *, void *);

listGetCompareMethod是一个函数,参数是(list *list)

返回值为 int(*)(void*, void*)函数指针