Yes you can do that in arrays, but only if its must.
Otherwise go for vectors as suggested by others.
Here is my answer in code:
#include <iostream>
using namespace std;
int main() {
//unitialise == garbage
cout << "*** Unitialised ***\n";
int* p1 = new int[3];
for(int i = 0; i < 3; i++)
cout << i << "\t" << p1[i] << endl;
// initialise individual elements
cout << "*** Initialise individual elements ***\n";
int* p2 = new int[3] { 1, 2, 3 };
for(int i = 0; i < 3; i++)
cout << i << "\t" << p2[i] << endl;
// initialise all elements
cout << "*** Initialise all elements ***\n";
int* p3 = new int[3] {0};
for(int i = 0; i < 3; i++)
cout << i << "\t" << p3[i] << endl;
//initialise all elements stack array
cout << "*** Initialise stack array ***\n";
int p4[3] = {0};
for(int i = 0; i < 3; i++)
cout << i << "\t" << p4[i] << endl;
delete[] p1;
delete[] p2;
delete[] p3;
return 0;
}
Here is the output:
*** Unitialised ***
0 6449456
1 0
2 3277144
*** Initialise individual elements ***
0 1
1 2
2 3
*** Initialise all elements ***
0 0
1 0
2 3277144
*** Initialise stack array ***
0 0
1 0
2 0
It is not possible to initialise all the elemets if you have allocated the array on heap, but you can do so if you have allocated it on stack.
My suggestion is that if you are sticking with arrays then use your existing code as it is cache friendly and will hardly take any time to execute.
You can find some interesting answers here and here.