奇怪的可变大小的数组声明 [英] Strange variable-sized array declaration

查看:126
本文介绍了奇怪的可变大小的数组声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个跳跃列表实现我碰到这个code片段来了

Reading this Skip List implementation I came across this code fragment:

typedef struct nodeStructure{
    keyType key;
    valueType value;
    node forward[1]; /* variable sized array of forward pointers */
    };

要我似乎转发[1] 表示一个元素的数组。并评论称这是的可变大小的数组的。

To me it seems that forward[1] denotes a one element array. And the comment calls it a variable sized array.

难道我误解的东西,或这只是我在看源的错误呢?

Do I misunderstand something or this is just a mistake in the source I'm reading?

推荐答案

这是旧的C编译器(C99之前)一个常用的技巧:允许你解引用元素编译过去年底前向的时候它是最后一个元素声明的长度结构;然后,您可以的malloc 足够的内存为其他节点元素,像这样的:

This is a common trick for the older C compilers (before C99): compilers allowed you to dereference elements past the end of forward's declared length when it is the last element of the struct; you could then malloc enough memory for the additional node elements, like this:

nodeStructure *ptr = malloc(sizeof(nodeStructure)+4*sizeof(node));
for (int i = 0 ; i != 5 ; i++) { // The fifth element is part of the struct
    ptr->forward[i] = ...
}
free(ptr);

诀窍让你嵌入结构变量大小的数组没有单独的动态分配。另一种解决方案是申报节点*转发,但你需要的malloc 免费它分别从 nodeStructure ,不必要地增加了一倍的malloc S的数量和无形中增加了内存碎片:

The trick lets you embed arrays of variable size in a structure without a separate dynamic allocation. An alternative solution would be to declare node *forward, but then you'd need to malloc and free it separately from the nodeStructure, unnecessarily doubling the number of mallocs and potentially increasing memory fragmentation:

下面是上面的片段会怎样看没有破解:

Here is how the above fragment would look without the hack:

typedef struct nodeStructure{
    keyType key;
    valueType value;
    node *forward;
};

nodeStructure *ptr = malloc(sizeof(nodeStructure));
ptr->forward = malloc(5*sizeof(node));
for (int i = 0 ; i != 5 ; i++) {
    ptr->forward[i] = ...
}
free(ptr->forward);
free(ptr);

修改(响应亚当罗森菲尔德评论):C99让你定义数组有没有大小,像这样:节点转发[]; 这就是所谓的EM>灵活的数组成员的,它是在C99标准的部分6.7.2.1.16定义<。

EDIT (in response to comments by Adam Rosenfield): C99 lets you define arrays with no size, like this: node forward[]; This is called flexible array member, it is defined in the section 6.7.2.1.16 of the C99 standard.

这篇关于奇怪的可变大小的数组声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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