Here is my code, I don't know what's wrong with it, why can't I new heap memory?
int*& mergeSort(int* A, int N) {
if (N == 1) {
return new int(A[0]); //error
}
int mid = N / 2;
int* A1 = mergeSort(A, mid);
int* A2 = mergeSort(A + mid, N - mid);
int* B = merge(A1, mid, A2, N - mid);
delete []A1;
delete []A2;
return B;
}
This code fails because it tries to return an lvalue reference to an rvalue. (The result of new
is an rvalue).
The simplest fix is to just have the function return int *
.
Without this fix, return B;
also leads to undefined behaviour because you have returned a reference to a local variable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.