30

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

Arno
  • 331
  • 2
  • 4
  • 8
  • 2
    Can't you use a `std::vector`? This would initialise all values to zero (or any other value you choose) – Nick Apr 24 '12 at 09:02
  • See the accepted answer here: http://stackoverflow.com/questions/7546620/operator-new-initializes-memory-to-zero – BoBTFish Apr 24 '12 at 09:04
  • Possible duplicate of [How can I make \`new\[\]\` default-initialize the array of primitive types?](https://stackoverflow.com/questions/2468203/how-can-i-make-new-default-initialize-the-array-of-primitive-types) – Aconcagua Nov 19 '18 at 06:58

6 Answers6

47

Sure, just use () for value-initialization:

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

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

Community
  • 1
  • 1
sharptooth
  • 167,383
  • 100
  • 513
  • 979
  • 2
    @shartptooth I tried that and get an error: error: ISO C++ forbids initialization in array new [-fpermissive] – Arno Apr 24 '12 at 09:09
  • @Arno that should compile. What compiler are you using? – juanchopanza Apr 24 '12 at 09:12
  • @juanchopanza GCC g++ compiler within eclipse cdt – Arno Apr 24 '12 at 09:13
  • @Arno maybe it is an old version. I have no problem with 4.6 or 4.7. – juanchopanza Apr 24 '12 at 09:15
  • @juanchopanza i'm running g++ 4.6.2. Maybe it's linked to the -fpermissive warning? – Arno Apr 24 '12 at 09:18
  • Fixed. I tried to put a value within the bracket and that's not working as expected. Anyway, problem solved! – Arno Apr 24 '12 at 09:23
  • @Arno not for me, fine with 4.6.1 and -fpermissive. Even with -pedantic-errors. – juanchopanza Apr 24 '12 at 09:24
  • I am getting error if I try to provide some value say 5. int* ptr = new int[4](5); – Forever Learner Apr 24 '12 at 09:50
  • @CppLearner That is intended. You can only initialize with `()` to zero. There is no way to initialize all instances to a value different then the default-value. – RedX Apr 24 '12 at 10:07
  • 1
    @CppLearner: you seem to be looking for [`std::uninitialized_fill`](http://en.cppreference.com/w/cpp/memory/uninitialized_fill) – Matthieu M. Apr 24 '12 at 10:54
  • @Matthieu M : Thanks for your inputs. Actually I was wondering if I can initialize dynamic array elements to some user specified value,say 5, using the single statement int *ptr = new int[4](5); //trying to initialize dynamic array of 4 elements with value 5. But itseems like,as pointed out by RedX that it is not possible. – Forever Learner Apr 25 '12 at 05:23
  • @CppLearner: Indeed it is not. For array you need to first allocate the storage and then initialize/assign the values you want. There are several STL algorithms designed for this. `uninitialized_fill` deals with raw storage and `copy` and `generate` allow to assign to existing objects. One more reason to have dirt-cheap default construction. – Matthieu M. Apr 25 '12 at 06:33
  • @sharptooth What about simple structures, say `stuct Point{int x; int y;};`? – John May 06 '22 at 08:02
6

I'd do:

int* a = new int[size];
memset(a, 0, size*sizeof(int));
Robert
  • 2,330
  • 29
  • 47
  • 6
    @Arno The proper way is sharptooth's answer. – Luchian Grigore Apr 24 '12 at 09:05
  • 1
    'without having to loop over all elements of the a array' - Isn't that effectively what you're doing with `memset`? Albeit that memset will no doubt be machine optimised. – Component 10 Apr 24 '12 at 09:09
  • 1
    @Component10: Yes, it will most certainly be optimised. But I agree with Luchian, the proper answer is sharptooth's. Bear in mind thought that even with that syntactically proper solution, the "memset" will be done "under the hood". – Robert Apr 24 '12 at 09:14
  • 1
    With GCC, the `memset` will generate a warning for non-[trivial](https://en.cppreference.com/w/cpp/types/is_trivial) types. Here, the `int` is trivial, so it works. For other types, that may have a non-default constructor, or default initialized fields, this will produce a warning, with a suggestion to use value initialization. – Daniel Stevens Feb 17 '20 at 00:56
4

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

Ross Rogers
  • 23,523
  • 27
  • 108
  • 164
Andriy
  • 8,486
  • 3
  • 27
  • 51
4

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
Andreas DM
  • 10,685
  • 6
  • 35
  • 62
3

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

THEOS
  • 59
  • 5
0
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.