
How to select an ideal array size in C? - AlbertJWilliams
So far I&#x27;ve seen so many pieces of code where arrays are declared with a seemingly random size, I mean, the size doesn&#x27;t seem to have a specific reason, but it seems more like a magic number.
How do I select the size for my arrays? Is it just about putting on a big number? I still don&#x27;t get it, and I feel like if I knew that, my code would get a lot better.
Thanks in advance.
======
nuclx
In common user-space non-realtime environments only use arrays, if you have
known bounds for the amount of elements. If an arbitrary number of elements is
needed, you need dynamic memory management anyways, so use linked lists. If
your requirements prohibit malloc (at all or after initialization), you need
to work with the available RAM as it suits your needs. Use fixed upper bounds,
but check for full arrays and report errors, if array bounds are exceeded.
This can be a bit of an art, especially when it comes to deciding what data to
keep on the stack, in global arrays or on the heap as well as choosing
approriate array sizes. Profile the RAM you need against what is available to
you and optimize array sizes to make best use of the available RAM.

~~~
mathieubordere
Dynamic memory management in no way implies linked lists.

~~~
asdjw0efjlka
He's a C programmer and they don't have generics, so they don't take advantage
of vectors, but when you point this out they will display a macro hack or
void* hack, then continue to use linked lists.

~~~
nuclx
Did you see the OP ask any questions about C++?

------
SamReidHughes
Generally speaking, you don't do this. You figure out the size you need and
allocate it dynamically. If you don't know the size, you use a dynamically
growing array type (that does the same thing as C++'s std::vector). E.g. use
asprintf (or implement your own using vsnprintf) as necessary. What you _don
't_ do is emulate the behavior of janky C programs that allocate a fixed size
array. That's bad.

(Sometimes you have arrays where the size doesn't affect the correctness of
your program. An example is if you're processing a file in chunks (e.g. to
compute ROT-13), then chunk size will affect performance, but not correctness.
You pick the size appropriate for your use case.)

------
swah
The good enough algorithm is "take a guess, then double every time a new
element doesn't fit". Really, just watch the whole Handmade Hero series..

------
krapp
This is my heuristic - make your best guess (you should have _some_ idea),
double it if you're uncertain, allocate the nearest power of 2 above that. If
during testing it turns out not to be large enough, realloc as necessary.

------
jventura
What do you want to insert on your arrays?! Numbers, characters? Could you
provide a specific example of what you want?

------
meh2frdf
Your best guess +1 ;)

~~~
meh2frdf
Really a down vote for a C joke, or did you not get it?

