+6  A: 

Yes there is:

std::vector<int> vec(SIZE, 0);

Use a vector instead of a dynamically allocated array. Benefits include not having to bother with explicitely deleting the array (it is deleted when the vector goes out of scope) and also that the memory is automatically deleted even if there is an exception thrown.

villintehaspam
this doesn't really answer the question that was asked.
John Knoeller
Should I always use `std::vector` instead of dynamically allocated arrays? What are the benefits of using an array over a vector, and vice versa?
dreamlax
I should have mentioned in my question, that the array must persist after the current scope. Do I have to use `new std::vector`?
dreamlax
@John Knoller: The OP asked about a C++ way to do it, I'd say that vector is the c++ way to do this. Of course, you are correct that there might be situations that still would call for a plain array and not knowing the OP's situation this might be one. I'd guess no though, since it seems plausible that the OP does not know about vectors.
villintehaspam
An array is somewhat faster, you control it fairly tightly. OTOH, you have to manage freeing the memory. When interfacing with C, sometimes you have to pass C functions an array. For most situations, vector is all you need.
Paul Nathan
@dreamlax: If it must persist after the scope, I would still prefer using a vector instead of an array. Only I would wrap it in a shared_ptr to make sure that it gets deleted. Using a shared_array is another option if you really must use a real array. (for a description of shared_ptr/shared_array, see www.boost.org).
villintehaspam
@villintehaspam: Although this solution doesn't answer my question it is the path I am going to take. Tyler McHenry answers my question more directly, and should help especially for people who cannot—for whatever reason—use `std::vector`.
dreamlax
@villintehaspam: what if you are the guy writing std:vector? what do you do then? _someone_ has to do the job rather than just punting it into a library.
John Knoeller
@John Knoeller: as I've pointed out many times before, you do NOT use a dynamically allocated array to implement `std::vector`. You use `::operator new` to allocate memory, and placement new to create objects in that memory -- it's substantially different, and `new[]` simply won't work (e.g., it immediately creates objects in all the memory allocated, which `std::vector` can't do).
Jerry Coffin
@Jerry: std::vector sure as hell doesn't use _stack_ allocation or _const_, so it must be dynamic allocation at some level. if the answer dreamlax's question is that new[] automatically inits the array, then it would be nice if someone actually _said_ that instead of deflecting.
John Knoeller
@villintehaspam: No, it is not a C++ way to do it. It is Java way to do it. Sticking `vector` everywhere regardless of context is called "Writing Java code in C++".
AndreyT
@John Knoeller: I was very specific in saying it doesn't use a dynamically allocated *array*. I already talked about what it does to allocate storage. The bottom line is that there's almost never any reason to use `new[]` -- even if you are the one implementing `std::vector` or something similar.
Jerry Coffin
@Jerry: Ok, I'll accept that. I've never had any use for new[], but I thought that was just me.
John Knoeller
@AndreyT: I agree that _always_ using vector over a dynamic allocated array isn't a good statement. However I would still argue that using a vector over a dynamically allocated array is the C++ way to do it and it should definitely be the preferred choice unless there is some particular reason to use a dynamically allocated array. This isn't writing Java code, it is getting the job done with minimal effort and lower risk of errors.
villintehaspam
+5  A: 

Assuming that you really do want an array and not a std::vector, the "C++ way" would be this

#include <algorithm> 

int* array = new int[n]; // Assuming "n" is a pre-existing variable

std::fill_n(array, n, 0); 

But be aware that under the hood this is still actually just a loop that assigns each element to 0 (there's really not another way to do it, barring a special architecture with hardware-level support).

Tyler McHenry
I don't mind if the loop is implemented underneath a function, I just wanted to know whether or not I had to implement such a loop myself. Thanks for the tip.
dreamlax
You might be surprised. I was. On my STL (both GCC and Dinkumware), std::copy actually turns into a memcpy if it detects it is being called with built in types. I wouldn't be surprised if std::fill_n used memset.
Brian Neal
Nope. Use 'Value-Initialization' to set all members to 0.
Martin York
+1  A: 

std::fill is one way. Takes two iterators and a value to fill the region with. That, or the for loop, would (I suppose) be the more C++ way.

For setting an array of primitive integer types to 0 specifically, memset is fine, though it may raise eyebrows. Consider also calloc, though it's a bit inconvenient to use from C++ because of the cast.

For my part, I pretty much always use a loop.

(I don't like to second-guess people's intentions, but it is true that std::vector is, all things being equal, preferable to using new[].)

brone
A: 

Typically for dynamic lists of items, you use a std::vector.

Generally I use memset or a loop for raw memory dynamic allocation, depending on how variable I anticipate that area of code to be in the future.

Paul Nathan
A: 

Do not use memset as memset works on bit level.

(I have not tried this). The efficient way of making your array of string is use the {}

int myArray[5] = {};

or

int myArray[5] = {0};

hope this helps.

The Elite Gentleman
What do you mean by "`memset` works on bit level"?
dreamlax
The question asked for how to initialise an array allocated using new, not how to initialise an automatic array of int (not string). The API for memset works at the byte level; the implementation usually works at the word level. Setting all bytes of an integer to zero will set the integer to zero.
Pete Kirkham
Well, Pete Kirkham explained what memset does.And as for my int myArray[5] = {} is equivalent to having int* myArray = new int[5]; except that I'm not using pointers to declare my arrays and an empty {} fills all records in the array with 0;
The Elite Gentleman
It binds the lifecycle of the array to the scope of the block it is declared in. The question is about how to initialise a dynamically allocated array; if the OP's problem could be solved with static arrays, then using initialisers would be fine, ( they often call memset under the hood ), but that's not what was asked.
Pete Kirkham
+3  A: 

If the memory you are allocating is a class with a constructor that does something useful, the operator new will call that constructor and leave your object initialized.

But if you're allocating a POD or something that doesn't have a constructor that initializes the object's state, then you cannot allocate memory and initialize that memory with operator new in one operation. However, you have several options:

1) Use a stack variable instead. You can allocate and default-initialize in one step, like this:

int vals[100] = {0};  // first element is a matter of style

2) use memset(). Note that if the object you are allocating is not a POD, memsetting it is a bad idea. One specific example is if you memset a class that has virtual functions, you will blow away the vtable and leave your object in an unusable state.

3) Many operating systems have calls that do what you want - allocate on a heap and initialize the data to something. A Windows example would be VirtualAlloc()

4) This is usually the best option. Avoid having to manage the memory yourself at all. You can use STL containers to do just about anything you would do with raw memory, including allocating and initializing all in one fell swoop:

std::vector<int> myInts(100, 0);  // creates a vector of 100 ints, all set to zero
John Dibling
A: 

you can always use memset:

int myArray[10];
memset( myArray, 0, 10 * sizeof( int ));
gbrandt
I understand that I can use `memset`, but I wasn't sure if this was the C++ way to approach the problem.
dreamlax
Yup, memset works just as well in C++ as in C for setting linear memory to a value.
gbrandt
It's not really the 'the C++ way', but then neither are raw arrays.
Pete Kirkham
@gbrandt - while that may be true, I wouldn't say it's "the C++ way". There are more "accepted" ways of doing it.
Smashery
@gbrandt:Which is to say that it doesn't work very well in either C or C++. It works for most values of the type is char or unsigned char. It works for most types of the value is 0 (at least in most implementations). Otherwise, it's generally useless.
Jerry Coffin
`10 * sizeof( *myArray )` is more documented and change-proof than `10 * sizeof( int )`.
Kevin Reid
In any case, the OP has a raw array and memset is the fastest and easiest way to zero that array.
gbrandt
A: 

There is number of methods to allocate an array of intrinsic type and all of these method are correct, though which one to choose, depends...

Manual initialisation of all elements in loop

int* p = new int[10];
for (int i = 0; i < 10; i++)
{
    p[i] = 0;
}

Using std::memset function from <cstring>

int* p = new int[10];
std::memset(p, 0, 10);

Using std::fill_n algorithm from <algorithm>

int* p = new int[10];
std::fill_n(p, 10, 0);

Using std::vector container

std::vector<int> v(10); // elements zero'ed

If C++0x available, using initializer list features

int a[] = { 1, 2, 3 }; // 3-element static size array
vector<string> v = { 1, 2, 3 }; // 3-element array but vector is resizeable in runtime
mloskot
+15  A: 

It's a surprisingly little-known feature of C++ (as evidenced by the fact that no-one has given this as an answer yet), but it actually has special syntax for default-initializing an array (well, technically, it's called "value-initialize" in the Standard):

new int[10]();

Note that you must use the empty parentheses - you cannot, for example, use (0) or any other expression (which is why this is only useful for default initialization).

This is explicitly permitted by ISO C++03 5.3.4[expr.new]/15, which says:

A new-expression that creates an object of type T initializes that object as follows:

...

  • If the new-initializer is of the form (), the item is value-initialized (8.5);

and does not restrict the types for which this is allowed, whereas the (expression-list) form is explicitly restricted by further rules in the same section such that it does not allow array types.

Pavel Minaev
+1 for teaching me something new.
John Dibling
While I agree that this is little-known, I can't (entirely) agree that it's really very surprising -- it was added in C++ 03, which most people seem to have nearly ignored (since this was one of the few new things it did add).
Jerry Coffin
@Jerry: I must admit that I didn't knew yet (probably because when I got to reading the standard, it was C++03 already). That said, it's remarkable that all implementations I know of support this (I guess it's because it's so trivial to implement).
Pavel Minaev
+1 I'm with John, something new!
gbrandt
@Pavel:Yes, it is pretty trivial to implement. As far as being new, *all* "value initialization" was new in C++ 03.
Jerry Coffin