I recently came across some posts about initializing arrays to 0 in C++. It seems that the recommended practice is to use code similar to the following:
1 2
char buffer[32] = { 0 };
char buffer[32] = {};
That got me wondering how it would work with dynamic arrays, specifically, of type double.
Say a C++ program accepts user input for the length, N, of an array, D1DArray, which will be created later dynamically. The array elements will all be assigned the value 0.0 at some point--but not at declaration. So the code snippets above would not be applicable. Is there a method comparably elegant to either of the methods above that assigns all elements of a dynamically-created array to 0.0? Here is what I have done so far (a manual assignment):
. . .
#include <vector>
. . .
int i, N;
vector<double> D1DArray; // Dynamic array of one dimension
. . .
cin >> N; //Input the size of the array to be created from the user
. . .
try { // Resize D1DArray array to its desired size
D1DArray.resize(N);
}
catch (bad_alloc& xa) {
cerr << "In catch block for resizing D1DArray array: " << xa.what() << "\n";
return 0;
}
for (i = 0; i < N; ++i) // Initialize all D1DArray elements to 0.0
D1DArray[i] = 0.0;
. . .
What is the "best practices" method of doing this?
It indicates that the more elegant way is to use the second method: char buffer[32] = {};
Similar discussions are posted on StackOverflow.
I suppose both your suggestions would work--if I moved the variable declaration to after input of the array size. Usually, I like to declare all variables before moving on to the body of the program (i.e., accepting user input, resizing, etc.) But your suggestions are workable.
I was just hoping for an elegant way of doing it similar to the material in the article.
After doing some additional reading and testing, I came across the statement that in C++, an empty initialization list initializes every element to 0.
I wonder if this applies if the initialization list is not there at all.
i.e., when the vector is resized to the size specified by the user input, are elements set to 0.0 by default? Does the C++ Standard say anything about this? Or is this behavior compiler dependent?
And does the same apply if the concept is extended to matrices of higher dimension? For example, say D2DArray is a 2-D array. A user then indicates he would like the dimensions of the array to be 25 x 45. When the array is resized, would all its elements be set to 0.0 by default?
When resizing a vector the new elements use the default value (which is 0 for built-in types). Also you can pass an argument to set the initial value of the new elements.
The default value is defined by the default constructor for classes.