Versions Compared

Key

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

...

Code Block
bgColor#ccccff
struct hack flexArrayStruct{
  int num;
  char my_char;
  int data[];
};

...
/* Space is allocated for the struct */
struct hackflexArrayStruct *hackPstructP = malloc(sizeof(struct hackflexArrayStruct) + sizeof(int) * ARRAY_SIZE);
if (!hackPstructP) {
     /* handle malloc failure */
}
hackP
/* Now, it is as if the struct were defined
	struct {int num; char my_char; int data[ARRAY_SIZE];} *structP;
and we can access the elements as if they were so. */
structP->num = SOME_NUMBER;
hackPstructP->my_char = SOME_CHAR;

/* Access data[] as if array had been allocated as data[ARRAY_SIZE] */
for (i = 0; i < ARRAY_SIZE; i++) {
  hackPstructP->data[i] = i;
}

No actual array space is allocated within the struct object. By mallocating space for the struct, the space computation is done at runtime, and allows the programmer to dynamically allocate space for an array within a struct.

...