How flexible is the array implemented in c?

..
char arKey[1]; } Bucket;

Above said what flexible array, how?

+3
source share
2 answers

Often the last member of the structure is assigned a size 0or 1(although it 0is against the standard pre-C99, it is allowed in some compilers, since it is of great importance as a marker). Since an array of size 0or is usually not created 1, this tells other colleagues that this field is used as the beginning of a variable-size array, starting from the end member and ending with any available memory.

, , , , .

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

0 C99. 1 C90 .

, malloc sizeof(Bucket) + array_length, array_length - . arKey ( ) , .

. :

http://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html

0

Source: https://habr.com/ru/post/1775138/


All Articles