没有动态内存分配的自引用(递归)结构

Self-referencial (recursive) struct with no dynamic memory allocation

我有一个表示 AST 的结构,我在嵌入式设备上,我没有 malloc,一切都应该在堆栈上或全局上。

所以我的结构;

/* AST Structre */
typedef struct ast {
    uint8_t type; /* This is the token value in grammar.h */

    /* Value of the token */
    union {
        double number;
        char literal;
    } value;

    struct ast *left; /* left hand side of the node */
    struct ast *right; /* right hand side of the node */
} ast_t;

我的问题是在没有 malloc 的情况下使用递归结构的最佳方法是什么。

只需创建一个数组并根据需要initialize/assign。

ast_t fred[] = { { 1, {2.0}, NULL,     &fred[1]}, 
                 { 3, {4.0}, &fred[0], NULL    } };

调用 ast_t 函数 foo(fred);。一定不要调用 free(fred).