Clearing array contents zeroing

suggest change

Sometimes it is necessary to set every element of an array to zero.

#include <stdlib.h> /* for EXIT_SUCCESS */

#define ARRLEN (10)

int main(void)
{
  int array[ARRLEN]; /* Allocated but not initialised, as not defined static or global. */

  size_t i;
  for(i = 0; i < ARRLEN; ++i)
  {
    array[i] = 0;
  }

  return EXIT_SUCCESS;
}

A common shortcut is memset from <string.h>. Passing array as shown below converts it to a pointer to its first element.

memset(array, 0, ARRLEN * sizeof(int)); /* Size of the explicit element type. */

or

memset(array, 0, ARRLEN * sizeof *array); /* Size of the element type. */

As in this example array is an array and not just a pointer to an array’s 1st element (see http://stackoverflow.com/documentation/c/322/arrays/1125/array-length#t=201701141205543540386 on why this is important) a third option to 0-out the array is possible:

memset(array, 0, sizeof array); /* Use size of the array itself. */

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents