int
array t with 5 elements:
int t[5];If the array is defined within a function, its content is unformatted. If, on the other hand, the table is defined at the global level, each element of it is initially 0.
int a[5] = {3,2,4,8,2};
int b[5] = {0}; // {0,0,0,0,0}
int c[5] = {1}; // {1,0,0,0,0}
n items,
the first index is 0 and the last index is n-1.
Here's how to work with an array:
t[0] = 5; t[1] = 2; t[2] = t[0]+t[1];The following code prints the array contents with a for loop:
for (int i = 0; i < n; i++) {
cout << t[i] << " ";
}
int t[4][7];To work with such a table:
t[0][0] = 2; t[2][1] = 5;
There are no pre-defined functions in the array, where its content could be treated as a whole. Thus, the contents of an array cannot be directly copied, compared, or printed, and none of the following codes work for arrays:
a = b;
if (a == b)
cout << t << "\n";If you need these features, they must be implemented by themselves, for example with a for loop.
In Chapter 14 we get to know the vector, which is a data structure like an array, but removes many of its limitations.
void test(int t[]) {
t[2] = 3;
}
int main() {
int t[5] = {0};
test(t);
cout << t[2] << "\n"; // 3
}
A function does not know how many items are in an array.
If this information is needed,
it must be passed separately as another parameter, for example:
void test(int t[], int n) {
for (int i = 0; i < n; i++) {
cout << t[i] << "\n";
}
}
int t[5]; t[100] = 2;This code creates an array with 5 elements, but then refers to the element at 100, which is outside the array. As a result, the program changes something in memory past the end of the array, which can lead to the program behaving strangely or crashing with an error.
Why doesn't C++ make sure the array is used correctly? The reason is performance: it would take time to check that the index is inside the array. C++ trusts that the programmer knows what they are doing.