C/C++ 一些值得记录的语法

广义表的头尾链表存储表示

这种储存形式没啥特别的意义,但其代码的写法有不少亮点:

/* ATOM==0:原子,LIST==1:子表 */
typedef enum { ATOM, LIST } ElemTag;

typedef struct GLNode {
    //公共部分,用于区分原子结点和表结点
    ElemTag tag;
    union {
        // 原子结点的值域
        AtomType atom;
        // 表结点的指针域
        struct {
            // hp和tp分别指向子表的表头和表尾
            struct GLNode *hp, *tp;
        }ptr;
    }a;
}*GList, GLNode;

枚举类型的用法:https://note.hzy.pw/3292.html

realloc

void *realloc( void *ptr, size_t new_size );
如果已经通过 malloc 函数获取到了动态的空间,想改变大小,可以使用 relloc 函数重新分配,
如果成功,返回新的地址,原指针 ptr 无效化,也不需要去 free 它。

通常的使用方法:
p = realloc(p, 128);

将函数作为参数传递

int out(int x, int inner(int a, int b) ) {
    return inner(x, 666);
}
int inner(int a, int b) {...}

out(123, inner);

指针类型的 typedef

typedef struct Node {
    int data;
    struct Node *next;
} Node, *pNode;

pNode head; //直接就是指针型

发布者

胡中元

《中原驿站》站长

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注