Salih Erikci Salih Erikci - 8 months ago 50
C Question

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

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));


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().