Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

What is a Flexible Array, exactly? I can't find much on it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
687 views
Welcome To Ask or Share your Answers For Others

1 Answer

There are a couple of things it could refer to. The only place I've seen that precise wording used much is C99 though.

A flexible array member is the official C99 name for what used to (usually) be called the "struct hack". The basic idea is that you define a struct something like this:

struct x {
    int a; // whatever members you want here.
    size_t size;
    int x[]; // no size, last member only
};

This is used primarily (or exclusively) with dynamic allocation. When you want to allocate an object of this type, you allocate enough extra space for whatever size of array you need:

struct x *a = malloc(sizeof(struct x) + 20 * sizeof(int));
a->size = 20;

The size member isn't strictly necessary, but often handy to keep track of the size allocated for a item. The one above has space for 20 int's, but the main point of this is that you might have several around, each with its own size.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...