What you could do is use calloc
, which is only one call, clearer to a lot of people, though not really a big deal, and uses the heap, which is the biggest benefit. Once you want to make really big array (or objects, or whatever), the heap is the place for you. Eventually, using the stack for this kind of stuff isn't practical, and will likely cause a stackoverflow error. Plus, you can pass this pointer returned from calloc
to anything with having to worry what will happen to that memory allocated. This is unlike the stack, where it will probably be overwritten once that function returns, something that has happened to me plenty of times, creating bugs that are super hard to fix. There are downsides, however, to calloc
like the fact that its pretty slow, but just as fast as memset
in this case. But if you don't really NEED all the bits to be set to 0, you could use malloc
(much faster and more popular). The second downside to calloc
or malloc
is that you must call free
on the pointers, otherwise you leak memory. Here's how to use calloc
:
#include <stdlib.h> // or "#include <cstdlib>" in C++
/* Allocate space for array, set all bytes to 0,
and return pointer. Then assign to long_array.
*/
unsigned long* long_array = (unsigned long*) calloc(ARRAY_SIZE);
// When you're done with this variable:
free(long_array);
Easy as that. Both calloc
and malloc
are made for this kind of stuff. I hope this helped!
Note: Though these links are to a C++ website, you can still use these functions in pure C by including <stdlib.h>