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