How to initialize a dynamic int array elements to 0 in C

Salih Erikci picture Salih Erikci · Jan 7, 2012 · Viewed 24.4k times · Source

I created a dynamic array ,and i need to initialize all the members to 0. How can this be done in C?

   int* array;
    array = (int*) malloc(n*sizeof(int));

Answer

Mysticial picture Mysticial · Jan 7, 2012

In this case you would use calloc():

array = (int*) calloc(n, sizeof(int));

It's safe to assume that all systems now have all zero bits as the representation for zero.

§6.2.6.2 guarantees this to work:

For any integer type, the object representation where all the bits are zero shall be a representation of the value zero in that type.

It's also possible to do a combination of malloc() + memset(), but for reasons discussed in the comments of this answer, it is likely to be more efficient to use calloc().