Arrays have the following advantages:
Random Access in O(1) Time: Arrays are stored in contiguous memory locations, which
means each element can be accessed using its index. This allows for quick access to
any element in the array using its index in O(1) time.
Cache Friendly: Modern computer architectures often employ a cache memory system
that stores frequently accessed data closer to the processor, allowing for faster
access times. Arrays are cache-friendly because they use contiguous memory
locations, which helps improve cache efficiency.
Efficiency: Arrays are very efficient in terms of memory usage and can be used to
store large amounts of data. They are also efficient for iterating over all the
elements in the array in sequence.
Easy to Implement: Arrays are simple and easy to implement in most programming
languages, making them a popular choice for storing and manipulating data.
**SWAP ARRAY**
int left = 0;
int right = n - 1;
while (left < right) //accesing full array without for
{
swap(arr[left], arr[right]);
left++;
right--;
}
for(int &element : arr) //generally
**Arrays to Fncs**
return_type name_of_function(data_type array_name[])
{
// function body
}
return_type name_of_function(data_type array_name[size])
{
// function body
}
return_type name_of_function(data_type *array_name)
{
// function body
}
**INSERTION IN ARRAY**
insertion in a invalid index causes the prg to **operation fails silently without
changing the array**
[arr]=arr[0]
arr[i]=*(arr+i)
accessing to out of index results in undefined behaviour(diff answers in diff
systems)
#define size 10
int arr[size]
int res = sizeof(arr[1]++) / sizeof(arr[2]++);
==>res = 1 and arr[1],arr[2] are their original values without increment
#define size 10000000
**The code is trying to create a very large array on the stack, which is causing
the runtime error.**
int k = ++(arr[0] + arr[1]); - This line attempts to use the pre-increment operator
on the result of arr[0] + arr[1]. However, this results in a compilation error
because the expression arr[0] + arr[1] is an rvalue (a temporary value), and you
cannot apply the pre-increment (or post-increment) operator to an rvalue. The
increment operators (++ and --) require an lvalue (a variable or something that has
a memory location) as their operand, as they modify the operand's value.
**2D ARRAYS** :
int arr[n][m];
int arr[][4] = {{ 312, 247, 311, 193 },
{ 311, 242, 738, 917 },
{ 941, 252, 549, 595 }};
int **arr;
arr = new int *[n];
for(int i = 0 ; i<n ;i++){
arr[i] = new int [m];
}
int *arr[n
];
for(int i = 0 ; i< n ;i++){
arr[i] = new int [m];
}
In C++, passing a 2-D array to a function can be done in multiple ways. Here are a
few examples:
const int n = 5;
const int m = 4;
void func_name(int a[N][M]) {
// your code
}
void func_name(int a[][5]) {
// your code
}
void func_name(int *a[5]) {
// your code
}
void func_name(int **a) {
// your code
}