Last active
December 22, 2015 11:39
-
-
Save exelotl/6466989 to your computer and use it in GitHub Desktop.
A macro that allocates and initialises memory simultaneously.
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
// allocate memory for a type, and initialise it at the same time | |
#define ialloc(t, ...) ialloc_impl(sizeof(t), &(t){ __VA_ARGS__ }) | |
// helper function | |
inline static void* ialloc_impl(int size, void* src) { | |
void* dest = malloc(size); | |
memcpy(dest, src, size); | |
return dest; | |
} | |
/* | |
// example usage: | |
int* a = ialloc(int, 5); | |
float* b = ialloc(float[4], 1.0, 4.1, 12, 1.3); | |
my_type* c = ialloc(my_type, .foo="hello world", .bar=1337); | |
// memory can then be freed like normal | |
free(a); | |
free(b); | |
free(c); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment