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));
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.
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.
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().
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. ...
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 ofnelemelements each of whose size in bytes iselsize. The space shall be initialized to all bits 0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With