Array BasicsΒΆ
Only local arrays (arrays declared as local variables) are discussed in this document.
Declaration and initialization:
int arr[10]; int arr1[10] = {}; int arr2[] = {1, 2, 3};
size must be specified unless it can be inferred from initialization
size must be a compilation-time constant
int literals:
10
pre-defined const variable:
const int SIZE = 4
Warning
Although variable as size is allowed with g++, it is not recommended as C++ standard does not allow that.
1// ---- correct ---- 2const int SIZE = 4; 3int arr3[SIZE]; 4 5// ---- wrong ---- 6int size = 4; 7int arr4[size];
Access the element:
1int sum = 0; 2int arr[4] = {1, 2, 3, 4}; 3cout << "The second element is " << arr[1] << endl; 4arr[1] = 12; 5cout << "Second element is set to " << arr[1] << endl;