代码之家  ›  专栏  ›  技术社区  ›  Prasoon Saurav

尾随数组习语

  •  10
  • Prasoon Saurav  · 技术社区  · 14 年前

    是什么 尾随数组习语 ?

    P.S:谷歌这个词给 向量是使用尾随数组惯用法实现的,因此在不更改向量对象本身的地址的情况下,它们不可调整大小。

    3 回复  |  直到 14 年前
        1
  •  10
  •   Fred Foo    14 年前

    如果您是指在 GCC source code (引用的地方),它似乎引用了实现动态数组的旧C技巧:

    typedef struct {
        /* header */
        size_t nelems;
    
        /* actual array */
        int a[1];
    } IntVector;
    

    创建数组的位置

    IntVector *make_intvector(size_t n)
    {
        IntVector *v = malloc(sizeof(IntVector) + sizeof(int) * (n-1));
        if (v != NULL)
            v->nelems = n;
        return v;
    }
    
        2
  •  1
  •   Darokthar    14 年前

    它似乎引用了结构中的数组,这些数组的大小可能是可变的。见:

    http://blogs.msdn.com/b/oldnewthing/archive/2004/08/26/220873.aspx http://sourceware.org/gdb/current/onlinedocs/gdbint/Support-Libraries.html

    另一个技巧是,如果你用谷歌搜索一个表达式,把它放在“类似”的“尾随数组”中,这会给你更具体的结果。谷歌知道跟踪数组。

        3
  •  1
  •   smilingthax    14 年前

    我认为这意味着:

    struct foo {
      ... some data members, maybe the length of bar ...
      char bar[]; /* last member of foo, char is just an example */
    };
    

    它是通过分配 malloc(sizeof(struct foo)+LEN) ,其中len是 bar . 只有这条路 需要malloc。这个 [] 只能与最后一个结构成员一起使用。

    而且,根据我对GCC文件的理解, struct foo 也只能(合理地)用作另一个结构的最后一个成员,因为存储大小不是固定的——或者用作指针。