logoalt Hacker News

A generic dynamic array in C that stores no capacity and needs no struct

11 pointsby alurmtoday at 2:50 AM19 commentsview on HN

Comments

procaryotetoday at 7:12 AM

Why would you want to avoid using a struct? Add a macro that declares the appropriate struct and get at least a tiny bit of type checking.

With some clever use of _Generic you could even build specialised functions for that type and get pretty good type checking

show 1 reply
dwrobertstoday at 6:58 AM

> First of all, structs aren't used so you don't have to invent names for them (e.g. there is no IntVec)

But since it’s storing a void pointer any way, they wouldn’t need separate names right? You could use one struct everywhere regardless of the type of the items

Which IMO is a better idea than using an array here because the fields can be properly named and typed to prevent accidental misuse

show 1 reply
t-3today at 5:22 AM

No structs, just an array that accomplishes the same thing, without field names or other niceties. Enjoy the pleasure of not using a struct when you inevitably add/reduce/reorder fields later.

show 1 reply
gritzkotoday at 5:24 AM

https://github.com/gritzko/libabc/blob/main/Sx.h

https://github.com/gritzko/libabc/blob/main/S.md

ABC uses s[2] for slices, g[3] for gauges, b[4] for (ring) buffers. Also containers on top of those (heaps, hash sets, etc etc)

userbinatortoday at 6:05 AM

capacity isn't stored at all. Instead, it's computed on demand when the length of the vec is either zero or a power of two.

Brilliant insight. This is the first time I've seen this observation in over 3 decades of working with C.

show 2 replies
doogliustoday at 6:34 AM

Strictly speaking, the capacity is still stored internally to the allocation (it needs to be, in order to implement realloc)

Akronymustoday at 6:11 AM

That's pretty clever code. Too clever for my tastes.

lefratoday at 6:43 AM

Enjoy the annoying-to-debug errors when someone inevitably mixes arr[0] with arr[1] and tramples the heap (this could be mitigated by accessing the fields with macros), or writes arr[3] because they forgot this is not a regular array.

show 1 reply
senderistatoday at 6:16 AM

This is just silly. You can't even reserve capacity because you only store size and capacity is implicitly the next power of 2 >= size.

show 1 reply