If you need an array of run-time size, then the proper approach depends on how large your array is going to be.
If the value of b
can be large, then declaring it as a local array can lead to stack overflow. In that case the better idea would be to dynamically allocate your array using calloc
. calloc
will properly zero-initialize an int
array.
If the array is relatively small and safe to allocate on the stack, the you can simply declare it as a local array (which is what you did in your original code) and then set it to all-zeros by using memset(arr, 0, sizeof arr)
.
Of course, in both cases you might end up with a hidden memory-zeroing cycle implemented inside the library function. In general case it is not possible to set a large region of memory to zero without using a cycle.