Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C, how do I create a `static` array of constant size with zeroed values, but without calloc?

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?

like image 780
Michael Bishop Avatar asked Aug 16 '13 23:08

Michael Bishop


1 Answers

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:

  • Global variables are automatically zero-filled (and do not need to be initialized if this is the intent).
  • The standard for uninitialized static objects in section 6.7.8.10 of the C99 standard says:

"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 it has pointer type, it is initialized to a null pointer;
  • if it has arithmetic type, it is initialized to (positive or unsigned) zero;
  • if it is an aggregate, every member is initialized (recursively) according to these rules;
  • if it is a union, the first named member is initialized (recursively) according to these rules."
like image 68
Jacob Pollack Avatar answered Sep 28 '22 01:09

Jacob Pollack