Below is a simple program to create an array that is the reverse of the passed array. The code throws the following error at line 6: Thread 1: EXC_BAD_ACCESS (code=1, address=0x7fff0000002c)
. The program compiles and the logic seems fine. Could someone explain my mistake?
void arrayReverser(int array[], int arrayLength) {
int arrayNew[arrayLength];
int current;
current = array[0];
for(int i = 0; current != '\0'; current = array[++i]) {
arrayNew[i] = array[arrayLength - i]; // Thread 1 error code occurs here
}
array = arrayNew;
}
int main() {
int array[] = { 2, 3, 4, 5, 6, 7 };
arrayReverser(array, 6);
}
It looks like you have two problems. First, your array reverser logic is for looping based on a terminator that does not exist in your array. You should instead loop based on array length.
Second, your arrayReverser function is allocating the return value (arrayNew) on the stack. Stack allocated local variables are automatically released when the method ends. You will need to allocate the return value on the heap to return it with new or malloc - and release it with delete/free in main.
If you prefer to keep the array in main intact, instead of using dynamic allocation, you could assign in place the values instead, like this:
This works, since it's re-using the sent in array for the result - and your "arrayNew" variable can safely be destroyed without being used. This "deep copy" of the array elements keeps the original array's allocation.