Arno
Arno

Reputation: 431

c++ initial value of dynamic array

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

Upvotes: 30

Views: 42973

Answers (6)

THEOS
THEOS

Reputation: 59

To initialize with other values than 0,

for pointer array:

int size = 10;
int initVal = 47;
int *ptrArr = new int[size];
std::fill_n(ptrArr, size, initVal);
std::cout << *(ptrArr + 4) << std::endl;
std::cout << ptrArr[4] << std::endl;

For non pointer array

int size = 10;
int initVal = 47;
int arr[size];
std::fill_n(arr, size, initVal);

Works pretty Much for any DataType!

!Be careful, some compilers might not complain accessing a value out of the range of the array which might return a non-zero value

Upvotes: 3

Andreas DM
Andreas DM

Reputation: 11028

Value initialize the elements with ()

Example:

int *p = new int[10];       // block of ten uninitialized ints
int *p2 = new int[10]();    // block of ten ints value initialized to 0

Upvotes: 4

Andriy
Andriy

Reputation: 8604

I'd advise you to use std::vector<int> or std::array<int,5>

Upvotes: 5

user1151738
user1151738

Reputation:

int *a=new int[n];
memset(a, 0, n*sizeof(int));

That sets the all the bytes of the array to 0. For char * too, you could use memset. See http://www.cplusplus.com/reference/clibrary/cstring/memset/ for a more formal definition and usage.

Upvotes: 0

sharptooth
sharptooth

Reputation: 170559

Sure, just use () for value-initialization:

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

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

Upvotes: 48

Robert
Robert

Reputation: 2389

I'd do:

int* a = new int[size];
memset(a, 0, size*sizeof(int));

Upvotes: 6

Related Questions