Reputation: 431
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
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
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
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
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