I need to dynamically create an array of integer. I've found that when using a static array the syntax
int a [5]={0};
initializes correctly the value of all elements to 0.
Is there a way to do something similar when creating a dynamic array like
int* a = new int[size];
without having to loop over all elements of the a array? or maybe assigning the value with a for loop is still the optimal way to go? Thanks
For instance, the integer arrays are initialized by 0 . Double and float values will be initialized with 0.0 . For char arrays, the default value is '\0' . For an array of pointers, the default value is nullptr .
The initialization of a dynamic array creates a fixed-size array. In the following figure, the array implementation has 10 indices. We have added five elements to the array. Now, the underlying array has a length of five. Therefore, the length of the dynamic array size is 5 and its capacity is 10.
When an array is created without assigning it any elements, compiler assigns them the default value. Following are the examples: Boolean - false. int - 0.
Sure, just use ()
for value-initialization:
int* ptr = new int[size]();
(taken from this answer to my earlier closely related question)
I'd do:
int* a = new int[size]; memset(a, 0, size*sizeof(int));
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