Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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));
like image 223
Salih Erikci Avatar asked Jan 07 '12 21:01

Salih Erikci


People also ask

What is dynamic initialization in array initialization in C?

Dynamic initialization of object in C++ Dynamic initialization of object refers to initializing the objects at a run time i.e., the initial value of an object is provided during run time. It can be achieved by using constructors and by passing parameters to the constructors.

How do you initialize all elements of a dynamic array to 0 in C++?

int* arrayMain = new int[arraySize-1] (); Note the () at the end - it's used to value-initialize the elements, so the array will have its elements set to 0.


3 Answers

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

like image 110
Mysticial Avatar answered Oct 22 '22 20:10

Mysticial


memset(array, 0, n*sizeof(int));

Or alternatively, you could allocate your block of memory using calloc, which does this for you:

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

calloc documentation:

void *calloc(size_t nmemb, size_t size);

The calloc() function allocates memory for an array of nmemb elements of size bytes each and returns a pointer to the allocated memory. The memory is set to zero. ...

like image 34
AusCBloke Avatar answered Oct 22 '22 21:10

AusCBloke


Use calloc function (usage example):

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

From calloc reference page:

void *calloc(size_t nelem, size_t elsize);

The calloc() function shall allocate unused space for an array of nelem elements each of whose size in bytes is elsize. The space shall be initialized to all bits 0.

like image 4
Eldar Abusalimov Avatar answered Oct 22 '22 21:10

Eldar Abusalimov