Array Initialization: Difference between revisions

→‎C++: I think this part is covered. Can someone else check the STL stuff?
(Creating and Array is being moved too)
(→‎C++: I think this part is covered. Can someone else check the STL stuff?)
Line 26:
Note that the array bounds, when unconstrained as in these examples can be either determined by the aggregate, like the initialization of X shows. Or else they can be specified as a constraint, like for example in the initialization of Y. In this case '''others''' choice can be used to specify all unmentioned elements. But in any case, the compiler verifies that all array elements are initialized by the aggregate. Single dimensional arrays of characters can be initialized by character strings, as the variable S shows. Of course, array aggregates can participate in array expressions and these expressions can be used to initialize arrays. The variable B is initialized by an aggregate inversed by the operation '''not'''.
==[[C++]]==
 
Simple arrays in C++ have no bounds-checking. In order to safely modify the array's contents, you must know in advance both the number of dimensions in the array and the range for each dimension. In C++, all arrays are zero-indexed, meaning the first element in the array is at index 0.
 
To assign a single value to an array, one uses the [] operator.
<lang cpp>
// Assign the value 7 to the first element of myArray.
myArray[0] = 7;
</lang>
If '''myArray''' has ten elements, one can use a loop to fill it.
<lang cpp>
// Assign the sequence 1..10 to myArray
for(int i = 0; i < 10; ++i)
myArray[i] = i + 1;
</lang>
If '''myArray''' has two dimensions, you can use nested loops.
<lang cpp>
// Create a multiplication table
for(int y = 0; y < 10; ++y)
for(int x = 0; x < 10; ++x)
myArray[x][y] = (x+1) * (y+1);
</lang>
 
===STL===
{{libheader|STL}}STL provides '''std::vector''', which behaves as a dynamically-resizable array. When an element is added, its value must be set immediately.
Anonymous user