在结构内部灵活的数组成员(C99) [英] Flexible array member (c99) inside a structure

查看:410
本文介绍了在结构内部灵活的数组成员(C99)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用这个code,而现在是,和它的作品很好,但它给了我一些头痛来实现它。它采用灵活的数组成员(FAM)又名结构体哈克。现在,C99具有使用可变长度阵列(VLA)的可能性,我不知道如何可以利用这片?

I've being using this code a while now, and it works fine, but it gave me some headache to implement it. It uses Flexible Array Member (FAM) aka Struct Hack. Now that C99 has the possibility of using Variable Length Array (VLA), I wonder how can I take advantage in this piece?

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;
}

(我在这里简化了整体结构和code,因为它使用两个结构,这并不是问题的重要,所以也许这个例子中有错误)

(I've simplified the whole struct and code here, because it uses two more structs that is not important to the question, so maybe this example has bugs )

现在,结构定义是在头文件(.H)和​​code创建一个语法树的编译器。我怎样才能改变阵列中使用的可变长度?

Now, the struct definition is in a header file (.h), and the code create a syntax tree for a compiler. How can I change the array to use variable length?

谢谢!
贝乔。

Thanks! Beco.

编辑:回滚最后篇]灵活的数组成员

Edited: rolling back the last editon to Flexible Array Member.

第2版。假设我添加函数里面这块code的:

2nd edition. Suppose I add inside the function this piece of code:

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;

我看

第一个问题,我返回一个指向一个局部变量。但是,这旁边,是富有成效的办法?
谢谢

First problem I see, I'm returning a pointer to a local variable. But beside that, is the way fruitful? Thanks

推荐答案

其实,这并不是说要在这里使用变长数组,但结构破解,又名不完全类型,又名灵活数组成员:

Actually, it's not variable-length arrays that you want to use here, but the struct hack, aka "incomplete types", aka the "flexible array member":

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

只有最后一个成员结构可能是灵活。

变长数组是一个不同的特点:

Variable-length arrays are a different feature:

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

(呵呵,这些东西被称为阵列,而不是矩阵。)

(Oh, and these things are called arrays, not matrices.)

这篇关于在结构内部灵活的数组成员(C99)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆