简体   繁体   中英

How do we create an array of structure, which has the flexible array as its last field?

Let's say we have:

struct A {
  int i;
  char c[1];
};

Usually I would use malloc() to create an instance of A, like:

#define LEN 10

struct A *my_A = malloc(sizeof(A) + LEN * sizeof(char));

But this would not work if I try to create an array of A

A struct with a flexible array member cannot be a member of an array. This is explicitly stated in section 6.7.2.1p3 of the C standard :

A structure or union shall not contain a member with incomplete or function type (hence, a structure shall not contain an instance of itself, but may contain a pointer to an instance of itself), except that the last member of a structure with more than one named member may have incomplete array type; such a structure (and any union containing, possibly recursively, a member that is such a structure) shall not be a member of a structure or an element of an array.

What you would need to do instead is declare the struct with a pointer instead of a flexible array member, and allocate space for each instance.

For example:

struct A {
  int i;
  char *c;
};

struct A arr[100];

for (int i=0; i<100; i++) {
    arr[i].c = malloc(LEN);
}

We don't.

One of the key characteristics of an array is that you know the offset between one element and the next, and you can't do that if the elements are variably-sized.

What you can create is an array of pointers to your flexibly-sized type. How each of the pointed-to objects is allocated is up to you.

It is possible to do what you have shown in your code just using a custom allocation / array iteration mechanism (you won't be able to use the default [] operator, though, because it determines the offset based on the size of the member), but I think that you don't want to do that.

In C/C++, a "flexible" array is just a pointer to an allocated piece of memory in the heap. What you would want to do in this case is this:

struct A {
  int i;
  char* c; // A pointer to an array
};

#define LEN 10
#define FLEX_ARRAY_LEN 20

struct A* my_A = malloc(sizeof(A) * LEN);
// initialize each array member
for (int i = 0; i < LEN; ++i) {
  // allocating new memory chunk for the flexible array of ith member
  my_A[i].c = malloc(sizeof(char) * FLEX_ARRAY_LEN);
}    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM