How to select an ideal array size in C?
So far I've seen so many pieces of code where arrays are declared with a seemingly random size, I mean, the size doesn'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't get it, and I feel like if I knew that, my code would get a lot better.
Thanks in advance.
13 comments
[ 3.2 ms ] story [ 46.4 ms ] threadIt depends on your application.
If your application is fine with returning failed allocations and can handle the case, then it's okay. But if you have a real-time or safety critical system, for example, something running on a vehicle, robot, or flying device, you usually can't risk failed allocations. In that case the better bet is to reserve memory on the heap for your array and ensure that you are within bounds or within a certain threshold by checking on push data to your array or using a circular buffer.
There are many approaches to solving a problem, and many ways to implement the solution, but the path you take usually depends on your application and your constraints. Think about which set of tradeoffs with respect to performance, safety, and memory usage makes the most sense for what you are trying to do.
(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.)