c - 结构内的灵活数组成员 (c99)

标签 c arrays c99

我已经使用这段代码一段时间了,它运行良好,但实现它让我有些头疼。它使用灵活数组成员 (FAM) 又名 Struct Hack。现在 C99 有可能使用可变长度数组 (VLA),我想知道如何在这 block 发挥优势?

typedef struct nO
{
    int oper;              /* some operator */
    int nops;              /* number of args */
    struct nO *ptn[1];     /* expansible array <=== HERE */
} nodoOper;

nodoOper *operator(int o, int n, ...)
{
    va_list ap;
    nodoOper *tn;
    size_t tam;
    int i;

    tam = sizeof(nodoOper) + (n - 1) * sizeof(nodoOper *); /* <=== AND HERE */

    if((tn=malloc(tam))==NULL)
        yyerror("Memory fault (cod. 4)");

    tn->oper = o;
    tn->nops = n;
    va_start(ap, n);
    for(i=0; i<n; i++)
        tn->ptn[i] = va_arg(ap, nodoOper*);
    va_end(ap);
    return tn;
}

(我在这里简化了整个结构和代码,因为它使用了两个对问题不重要的结构,所以这个例子可能有错误)

现在,结构定义在头文件 (.h) 中,代码为编译器创建语法树。如何更改数组以使用可变长度?

谢谢! 成为。

已编辑:将上次编辑回退到灵活数组成员。

第二版。假设我在函数中添加了这段代码:

struct nOp
{
    int oper;             /* some operator */
    int nops;             /* number of args */
    struct nOp *ptn[n];   /* Variable Length Array (VLA) */
};
struct nOp tnop;
struct nOp *tn2;

tn2 = &tnop;
return tn2;

我看到的第一个问题是,我返回了一个指向局部变量的指针。但除此之外,这条路是否富有成效? 谢谢

最佳答案

实际上,您要在此处使用的不是可变长度数组,而是 struct hack,又名“不完整类型”,又名“灵活数组成员”:

typedef struct nO
{
    int oper;
    int nops;
    struct nO *ptn[];  // <== look ma, no index!
} nodoOper;

// skip a bit
// no more (n-1) --------\
tam = sizeof(nodoOper) + n * sizeof(nodoOper *);

只有 struct 的最后一个成员可能是“灵活的”。

可变长度数组是一个不同的特性:

void foo(int size)
{
    float a[size];               // run-time stack allocation
    printf("%lu\n", sizeof(a));  // and run-time sizeof (yuck)
}

(哦,这些东西叫做数组,不是矩阵。)

关于c - 结构内的灵活数组成员 (c99),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5478706/

相关文章:

c - c语言中的右移。

c - union 类型和灵活的数组成员

c - 退格字符被添加到 FIFO 中

c - 将指向 putchar 的指针传递给接收 int (*)(int) 的函数

android - String[] a 和 String a[] 的区别

php - 将数据库查询结果格式化为 JSON 数组并读入表单

C 编译器和 C99 标准

c - 使用 fscanf 从文件读取并保存到 struct c 语言的数组中

c - 练习6-4 C 语言编程

php - 在 PHP 中使用 foreach 解析 JSON