Various ways of initializing the Arrays.
- The for loop initializes 10 elements with the value of their index.
void main()
{
const int size = 10;
int arr[size];
for(int i = 0; i < size ; i++ ) // You can declare a
variable here in C++.
{
arr[i] = i;
}
}
- An array can be explicitly initialized as follows.
e.g.
int arr[3] = {0,1,2};
- An explicitly initialized array need not specify size but if specified the number of elements provided must not exceed the size. If the size is given and some elements are not explicitly initialized they are set to zero
e.g.
int arr[] = {0,1,2};
int arr1[5] = {0,1,2}; // Initialized as {0,1,2,0,0}
const char a_arr1[] = {'c'.'+','+'} //size = 3;
const char a_arr2[] = {"c++"} //size = 4 because of
null character at the
end of the string;
const char a_arr3[6] = "Daniel"; // ERROR; Daniel has 7 elements