I tried to call your function like this (without changing anything in it):
void rearrange(long long *arr, int n)
{
long long temp[n];
int max = n - 1;
int min = 0;
for(int i = 0;i < n;i++) {
if(i%2 == 0) {
temp[i] = arr[max];
max--;
} else {
temp[i] = arr[min];
min++;
}
}
for(int i = 0;i < n;i++) {
arr[i] = temp[i];
}
}
int main()
{
const int n = 10;
long long arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
rearrange(arr, n);
return 0;
}
and the compiler g++ 9.3.0
showed no errors and the SIGSEG
signal wasn't raised.
But!
Your function has weaknesse. Modern C++ compilers allow you to declare an array the way you did:
long long temp[n];
The weakness is in a fact that the value of the variable n
is unknown during compilation. It's a bad C++ way. It's better to do like that (if the C-style arrays are your choice):
void rearrange(long long *arr, int n)
{
long long *temp = new long long[n];
...
...
...
delete temp;
}
In addition, you may have called a function and passed it a pointer arr
pointing to a random memory location, i.e. did not allocate memory for the array. For example, if you call your function with such an uninitialized pointer, the OS will initiate a signal SIGSEG
(Segmentation Fault):
int main()
{
const int n = 10;
long long *arr; // pointing to any (unknown) memory cell
rearrange(arr, n);
return 0;
}
But in this case g++
shows warning message: ‘arr’ is used uninitialized in this function (main).