开发者

What is a Flexible Array?

开发者 https://www.devze.com 2022-12-28 07:24 出处:网络
What is 开发者_如何学运维a Flexible Array, exactly? I can\'t find much on it.There are a couple of things it could refer to. The only place I\'ve seen that precise wording used much is C99 though.

What is 开发者_如何学运维a Flexible Array, exactly? I can't find much on it.


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.


There isn't such thing as a flexible array, but there is such thing as a flexible array member. It is used to provide access to variable-length data as a member of a struct.

From http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=/com.ibm.xlcpp8a.doc/language/ref/strct.htm:

A flexible array member, which is a C99 feature, can be an element of a structure with more than one named member. A flexible array member can be used to access a variable-length object. The flexible array member must be the last element of such a structure, and it has incomplete type.


A flexible array is an array whose index bounds are determined at run time and may change during the lifetime of the array.

Java arrays are flexible. For example, in Java you can assign one array to another:

int[] a1 = {1, 2, 3, 4};
int[] a2 = {1, 2, 3};
a1 = a2;

At first, a1 has index range 0–3, and a2 has index range 0–2.

After the assignment a1 = a2, a1 points to an array with index range 0–2, so the index range of a1 varied during the lifetime of a1.


Does this describe what you are asking about? This is not unique to Sun's C compiler, but it was the first clear overview I found:

Sun Studio 12 Update 1: C User's Guide: Flexible Array Members


Flexible array members are indispensable tools in network programming. In network programming, you never know the data size in advance.

For example, you are writing a code to supply the entire ROUTING TABLE for some reasons. You never know how many routes are there beforehand and allocating maximum supported will hamper your code severely. The safest bet is to declare the flexible array member and cook all your data and fire it once.

0

精彩评论

暂无评论...
验证码 换一张
取 消