Versions Compared

Key

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

...

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

...
/* Space is allocated for the struct */
struct hack * hackP = malloc( sizeof(struct hack) + sizeof(int) * (ARRAY_SIZE-1) );
if(!hackP) {
	     /* handle malloc failure */
}
hackP -> num = SOME_NUMBER;
hackP -> my_char = SOME_CHAR;

/* Access data[] as if it had been allocated as data[ARRAY_SIZE] */
for(i=0; i<ARRAY_SIZE; i++)
	     hackP -> data[i] = i;

Wiki Markup
This is, strictly speaking, undefined behavior when accessing hackP->data\[i\] for i>0, since that goes beyond the bounds of the array.

...

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

...
/* Space is allocated for the struct */
struct hack * hackP = malloc( sizeof(struct hack) + sizeof(int) * ARRAY_SIZE );
if(!hackP) {
	     /* handle malloc failure */
}
hackP -> num = SOME_NUMBER;
hackP -> my_char = SOME_CHAR;

/* Access data[] as if array had been allocated as data[ARRAY_SIZE] */
for(i=0; i<ARRAY_SIZE; i++)
	     hackP -> 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.

...