0

Here's the code, I'm getting a run-time error and I'm very confused.

int* reversearray(int *a, int sz){
    int* array = new int[sz];
    for(int i = 0 ; i < sz; ++i){
        array[i] = a[i];
    }
    delete [] a;
    a = NULL;
    return array;
}

int main() {
    int size = 5;
    int hello[size] = {1 , 2, 3, 4 ,5};
    int* p = hello;
    int* q = reversearray(p, size);
    return 0;
}
  • What is your question? Is it "How do I fix this runtime error?"? (In that case you should describe the error) – user253751 May 08 '17 at 04:38
  • 3
    P.S. I can already see the problem with the code, but I want you to think about the question first. – user253751 May 08 '17 at 04:38
  • 1
    You're calling `delete` on an array that you didn't allocate with `new`. – Weak to Enuma Elish May 08 '17 at 04:38
  • Yes, I'm getting a runtime error and I don't know where – Kyle Grewe May 08 '17 at 04:40
  • 1
    `int hello[size]` is needlessly a [Variable Length Array](https://en.wikipedia.org/wiki/Variable-length_array) – user4581301 May 08 '17 at 04:40
  • 1
    And the elephant in the room: [`std::reverse`](http://en.cppreference.com/w/cpp/algorithm/reverse) – user4581301 May 08 '17 at 04:41
  • 1
    Think on the naming. Why would a function called `reversearray`, create a new array, copy the source array into the new array, and delete the source? That seems like a bit of over-reach for a function that one would expect simply reverses an array in place. [When you break the Law of Least Surprise](https://en.wikipedia.org/wiki/Principle_of_least_astonishment) you get bugs. For example, what if a caller, quite reasonably, expected the array they provided to be cloned but remain usable after the reversal? It is their array after all. – user4581301 May 08 '17 at 04:51

0 Answers0