4 ms·
Probably more efficient to store the data array inline, with a flexible array member. That way creating takes only one malloc, and destruction only one free.
by im3w1l 10y ago
Probably more efficient to store the data array inline, with a flexible array member. That way creating takes only one malloc, and destruction only one free.
- krylon 10y agoThose are great. I haven't used C a lot in a long time, but I remember back when I wrote C code for a living that I ran into the exact situation flexible array members are made for around the time I also learned of them. "That will solve my problem elegantly", I thought, but unfortunately, the compiler we used only understood C89, so my hands were tied.
- userbinator 10y agobut unfortunately, the compiler we used only understood C89, so my hands were tied. You can do it in C89 too, just allocate sizeof(header) + n * sizeof(element).
- krylon 10y agoYes, but it's not the same. :( { It is fun, though - I once did it to write/read a data structure with two levels of indirection (i.e. an array of arrays) - Slurp the whole thing to memory, then adjust the pointers, and voila. } In C89 it's trickery and a little bit of black magic (at least a whiff of it), while in C99, it is an officially supported convention. On x86, where the C code I wrote ran, it wouldn't make much of a difference, but allocating header + array manually also means - if the code needs to run across a variety of CPU architectures - that one needs to look at alignment issues.
- makapuf 10y agoIIRC You don't have to play with pointers if you use the null array trick (put an array of size zero at the end of your struct and use it anyway)
- AlexeyBrin 10y agoYes, but you can't use flexible array members with a void array. So you will need to have a specialized structure for every data type (or use some macro system to generate these). It is an excellent alternative for numerics when you usually work with simple types like int and double.