Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ initial value of dynamic array

Tags:

c++

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

like image 297
Arno Avatar asked Apr 24 '12 09:04

Arno


People also ask

What is the initial value of array in C?

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 .

What is a dynamic array initialization?

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.

What is the default value in an array?

When an array is created without assigning it any elements, compiler assigns them the default value. Following are the examples: Boolean - false. int - 0.


2 Answers

Sure, just use () for value-initialization:

 int* ptr = new int[size](); 

(taken from this answer to my earlier closely related question)

like image 66
sharptooth Avatar answered Oct 11 '22 18:10

sharptooth


I'd do:

int* a = new int[size]; memset(a, 0, size*sizeof(int)); 
like image 44
Robert Avatar answered Oct 11 '22 19:10

Robert