r/C_Programming • • 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

16 comments sorted by

View all comments

Show parent comment

1

u/TheChief275 May 20 '26

It doesn't even need to be that complicated either. A simple bit twiddling hack that works is:

--cap;
for (unsigned i = 1; i != sizeof(cap) * 8; i <<= 1)
    cap |= cap >> i;
++cap;

which rounds a number to the nearest power of 2 in constant time.

The compiler should unroll this, but if not, unrolling it manually is easy as well

3

u/pjl1967 May 20 '26

IMHO, your code looks more complicated than mine. Also, your code doesn't make cap the smallest power of two ≥ len — your code doesn't use len at all so it's not clear to me what it's doing.