r/C_Programming • u/pjl1967 • May 20 '26
My own bare-bones dynamic array
About a month ago, somebody posted asking for design advice for a dynamic array. My then advice was to treat the element type as an opaque type T.
I've had my own implementation of such a dynamic array lying around for a while, but finally had a use for it, so I gave it a bit of polish and it's here:
If you wanted it to be even more bare-bones, you could keep only the regular (bounds-checking) functions or the no-check (_nc) functions, whichever you prefer.
10
Upvotes
•
u/AutoModerator May 20 '26
Hi /u/pjl1967,
Your submission in r/C_Programming was filtered because it links to a git project.
You must edit the submission or respond to this comment with an explanation about how AI was involved in the creation of your project.
While AI-generated code is not disallowed, low-effort "slop" projects may be removed and it's likely that other users push back strongly on substantially AI-generated projects.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
4
u/WittyStick May 20 '26
You can do this more efficiently without branching using bit tricks. Since your array starts at length 2 (
0b10), and you increase capacity by shifting left, the capacity should always be a power of 2, which we can test for usingpopcount(len) == 1.To get the next power of 2 above a given length, we have
stdc_bit_ceil(len)(Use__builtin_stdc_bit_ceilin GCC if <stdbit.h> isn't present).bit_ceilis implemented in using count leading zeros.In fact, if you use this doubling capacity strategy, you don't even need to store
capin the struct, as it can be computed fromlenon the fly - you just need to make sure you shrink the cap if length becomes smaller than the next lowest power of 2 (stdc_bit_floor).1
u/Certain-Flow-0 May 21 '26
It seems that your reserve() function expects the number to be a delta, which takes len into consideration. This is quite different from vector.reserve() which expects the resulting new capacity, ignoring len.
1
u/Certain-Flow-0 May 21 '26
I guess I missed to ask this more important question:
Why is reserve() dependent on the current length and why does it make capacity the lowest power of two that’s greater than or equal to length?
As far as I know, capacity should be independent of the length because it allows use-cases where I want to reserve 1024 elements upfront, not just 2. The added logic in reserve just makes it more complicated, slower, and misses the use-case above.