I currently have some code in a function that looks like this:
static const int kFrameCountSample = 250;
static float * samples = (float *)calloc(kFrameCountSample, sizeof(float));
I like that the samples array is zeroed out exactly once with calloc()
.
I can also write the code so samples
is allocated on the stack.
static const int kFrameCountSample = 250;
static float samples[kFrameCountSample];
but now samples
is not initialized to zero values. How would I also initialize it at the time it is allocated?
For completeness (note: this is C99 NOT C++):
It's important to note that if you define and initialize a static array of length k
to less than k - 1
values then the rest will be zero-filled. Hence:
static float samples[kFrameCountSample];
... is identical to:
static float samples[kFrameCountSample] = { 0 }; // Zero-fills.
... and will zero-fill samples
. Moreover, if you do the following:
static float samples[kFrameCountSample] = { 1, 2, 3 }; // Zero-fills elements of position 3 ... 250.
... it will zero-fill the rest of the elements that are not assigned in the initialization of samples
.
Remark:
"If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With