Skip to content

Instantly share code, notes, and snippets.

@manjuraj
Created October 18, 2011 23:36
Show Gist options
  • Save manjuraj/1297075 to your computer and use it in GitHub Desktop.
Save manjuraj/1297075 to your computer and use it in GitHub Desktop.
C struct hack
#include <stdlib.h>
#include <stddef.h>
/*
* C struct hack - the last member of the struct is of variable length
*
* C99 however introduces the concept of a flexible array member, which
* allows the size of an array to be omitted if it is the last member
* in a structure
*/
struct s {
int n;
char a[1];
};
int
main(void)
{
struct s *p;
int i, n = 100;
size_t size;
size = offsetof(struct s, a) + n * sizeof(p->a[0]);
/* size = sizeof(*p) - 1 + n * sizeof(p->a[0]); */
p = malloc(size);
p->n = n;
for (i = 0; i < n; i++) {
p->a[i] = 'A' + (i % 26);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment