Arrays properties in c++
1- Declaration and Initialization:
You declare an array by specifying its type and name, followed by square brackets containing its size. Initialization can be done at the time of declaration or later using an initializer list.
int myArray[5] = {1, 2, 3, 4, 5};
2- Indexing:
Array elements are accessed using indices starting from 0.
int value = myArray[2]; // Accesses the third element
3-Contiguous Memory:
Array elements are stored in contiguous memory locations. 4-4-Size:
The size of an array is fixed at the time of declaration and cannot be changed during runtime.
5-Zero-Based Indexing:
Indices start from 0, so the first element is at index 0, the second at index 1, and so on.
6-Element Access:
Individual elements can be accessed using square brackets and the index.
7-Memory Efficiency:
Arrays are memory-efficient, as they allocate a fixed amount of memory for a specific number of elements.
8-Sizeof Operator:
You can use the sizeof operator to determine the size of an array in bytes.
int size = sizeof(myArray) / sizeof(myArray[0]);
9-Looping Through an Array:
Commonly, loops such as for or while are used to iterate through array elements.
for (int i = 0; i < 5; ++i) {
// Process myArray[i]
}
10-Multidimensional Arrays:
C++ supports multidimensional arrays (arrays of arrays).
int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
```
11-Array Decay:
When an array is passed to a function, it "decays" into a pointer to its first element.
void myFunction(int arr[]) {
// ...
}
```
- Standard Library Alternatives:
C++ also provides dynamic arrays like std::vector and other container classes in the Standard Template Library (STL), which offer more flexibility and functionality. Remember that arrays in C++ have some limitations, such as fixed size and lack of built-in safety checks for bounds, which can lead to undefined behavior if not used carefully.