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 correctl
I'd advise you to use std::vector<int>
or std::array<int,5>
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
I'd do:
int* a = new int[size];
memset(a, 0, size*sizeof(int));
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.
Sure, just use ()
for value-initialization:
int* ptr = new int[size]();
(taken from this answer to my earlier closely related question)
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