Skip to content

Instantly share code, notes, and snippets.

@yuba
Created November 6, 2015 03:14
Show Gist options
  • Save yuba/2e47676e941f65ba0ff3 to your computer and use it in GitHub Desktop.
Save yuba/2e47676e941f65ba0ff3 to your computer and use it in GitHub Desktop.
可変長構造体をmalloc()使わないで確保 ref: http://qiita.com/yuba/items/5e894ea9f12ba3fe354b
// つまり、長さ256の配列を確保するのに
int int_array[256];
// でなく
int* int_array = (int*)malloc(256);
// なんてやるのは
struct sizable {
size_t length;
int contents[1];
}
sizable* s = (sizable*)malloc(sizeof(sizable) + (256-1) * sizeof(int));
s->length = 256;
// s を使ってなんかAPIを呼び出している
free(s);
struct sizable_256 {
sizable base;
int dummy[256 - 1];
};
struct sizable_256 {
sizable base;
int dummy[256 - 1];
};
sizable_256 s{ sizable { 256 } }; // s.base.length を256に初期化している
// &s.base を使ってなんかAPIを呼び出している
// freeしなくていいよ!
struct {
sizable base;
int dummy[256 - 1];
} s{ sizable { 256 } }; // s.base.length を256に初期化している
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment