3 ms·
I think it's cleaner to allocate the header information before the actual pointer (or, conversely, to return the pointer sizeof(array_header) into the allocatio
by phs2501 10y ago
I think it's cleaner to allocate the header information before the actual pointer (or, conversely, to return the pointer sizeof(array_header) into the allocation). Then it's trivial to pass around.
struct vec_header_t {
size_t length;
size_t capacity;
};
static inline struct vec_header_t *vec_to_header(void *vec)
{
return ((struct vec_header_t *)vec) - 1;
}
#define _vec_length(vec) (vec_to_header(vec)->length)
static inline void vec_free(void *vec)
{
if (vec)
free(vec_to_header(vec));
}
#define vec_foreach(vec, iter) \
for ((iter) = (vec); (iter) < ((vec) + vec_length(vec)); ++(iter))
It's slightly more cognitive overhead when, for example, debugging, but the vast improvement in usability (no special macros for normal/static declaration, trivial passing to functions, etc) is worth it IMHO.
- to3m 10y agoCompared to the code in the linked post, I guess I'm a lot more strongly in favour of type safety, which this solution has too. But as a bear of very little brain, I really must insist on no extra cognitive overhead while debugging! Sadly there's no really good way of doing this in C, so whatever you do there's a tradeoff somewhere. You just have to decide what type of crap you want to put up with, and code accordingly ;) (If you're working on your own, I do say this is a fair argument for at least giving C a go when you might otherwise have gone with C++. If you can come up with some stuff that doesn't annoy you in any way you care about, and you don't mind the fact that C lacks a few of C++'s creature comforts, you'll reap the benefit of hilariously better build times.)