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

Categories

0 votes
757 views
in Technique[技术] by (71.8m points)

language agnostic - What is a Flexible Array?

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

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...