How's flexible array implemented in c?
..
char arKey[1]; } Bucket;
The above is said to be flexible 开发者_如何学Goarray
,how?
Often the last member of a struct is given a size of 0
or 1
(despite 0
being against the standard pre-C99, it's allowed in some compilers as it has great value as a marker). As one would not normally create an array of size 0
or 1
, this indicates to fellow coders that the field is used as the start of a variably sized array, extending from the final member into any available memory.
You may also find a member of the struct defining the exact length of the flexible array, just as you often find a member that contains the total size in bytes of the struct.
Links
- http://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html
- Is using flexible array members in C bad practice?
- http://msdn.microsoft.com/en-us/library/6zxfydcs(VS.71).aspx
- http://blogs.msdn.com/b/oldnewthing/archive/2004/08/26/220873.aspx
Example
typedef struct {
size_t len;
char arr[];
} MyString;
size_t mystring_len(MyString const *ms) { return ms->len; }
MyString *mystring_new(char const *init)
{
size_t len = strlen(init);
MyString *rv = malloc(sizeof(MyString) + len + 1);
rv->len = len;
strncpy(rv->arr, init, len);
return rv;
}
Flexible arrays are supposed to have a length of 0 in C99. Using a size of 1 is C90 and is now deprecated.
Basically, such flexible arrays are created by invoking malloc
with sizeof(Bucket) + array_length
, where array_length
is the desired size of your array. Then, dereferencing the arKey
pointer (which must be the last member of your structure) will result in that extra memory being accessed, effectively implementing variable-sized objects.
See this page for more information:
http://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html
精彩评论