简体   繁体   English

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

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

I have a struct to represent an AST, and I'm on an embedded device, I have no malloc, everything should be either on stack or global.我有一个表示 AST 的结构,我在一个嵌入式设备上,我没有 malloc,一切都应该在堆栈上或全局上。

So my struct;所以我的结构;

/* 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;

My question is whats the best way to use recursive structs without malloc.我的问题是在没有 malloc 的情况下使用递归结构的最佳方法是什么。

Simply create an array and initialize/assign as needed.只需创建一个数组并根据需要进行初始化/分配。

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

Call the ast_t functions foo(fred);调用ast_t函数foo(fred); . . Be sure to not call free(fred) .一定不要打电话给free(fred)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM