Created
October 18, 2011 23:36
-
-
Save manjuraj/1297075 to your computer and use it in GitHub Desktop.
C struct hack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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