3 ms·
Those 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
by krylon 10y ago
Those 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)