Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#ccccff
struct flexArrayStruct *structP;
size_t array_size;
size_t i;

/* Initialize array_size */

/* Space is allocated for the struct */
structP = (struct flexArrayStruct *)
   malloc(sizeof(struct flexArrayStruct) + sizeof(int) * array_size);
if (structP == NULL) {
  /* Handle malloc failure */
}

structP->num = 0;

/*
 * Access data[] as if it had been allocated
 * as data[array_size]
 */
for (i = 0; i < array_size; i++) {
  structP->data[i] = 1;
}

Prior to the introduction of flexible array members in the C99 standard, structures with a one element array as the final member were used to achieve similar functionality. The following code example illustrates how struct flexArrayStruct is declared in this case.

Code Block
bgColor#FFcccc

struct flexArrayStruct {
  int num;
  int data[1];
};

The approach to acquiring memory in this case is similar to the C99 approach with the exception that 1 is subtracted from array_size to account for the element present in the structure definition. The problem with using this approach is that the behavior is undefined when accessing other than the first element of data (see Section 6.5.6, Paragraph 8 of the C99 standard).  Consequently, the compiler can generate code that does not return the expected value when accessing the second element of data.  Structures with flexible array members can be used to produce code with defined behavior.  However, some restrictions apply:

...