Advertisements

I know I should be using vectors, but I want to get better at dynamically allocating arrays. I’m not sure where I went wrong. I’m creating a new array and deleting it.

```
void Merge(int *arr,int begin, int mid, int end){
int*arrB = new int[mid - begin + 1];
int i = begin;
int j = mid+1;
int k = 0;
while(i <= mid && j <= end){
if(arr[i] <= arr[j]){
arrB[k] = arr[i];
k++;
i++;
}
else {
arrB[k] = arr[j];
k++;
j++;
}
}
while(i <= mid){
arrB[k] = arr[i];
i++;
k++;
}
while(j <= end){
arrB[k] = arr[j];
j++;
k++;
}
k = 0;
for(int i = begin; i <= end; i++){
arr[i] = arrB[k];
s.setData(arr);
k++;
}
delete[] arrB; //error here
}
```

I’ve tried replacing <= to < for n-1, I’ve tried switching to vectors and that also gives me an error. I’ve also tried looking at similar questions.

### >Solution :

```
void Merge(int *arr, int begin, int mid, int end) {
// Allocate the arrB array on the stack instead of the heap
int arrB[mid - begin + 1];
int i = begin;
int j = mid+1;
int k = 0;
// Initialize the k variable to 0 before using it to index arrB
k = 0;
while (i <= mid && j <= end) {
if (arr[i] <= arr[j]) {
arrB[k] = arr[i];
i++;
} else {
arrB[k] = arr[j];
j++;
}
// Increment the k variable after each element is added to arrB
k++;
}
while (i <= mid) {
arrB[k] = arr[i];
i++;
k++;
}
while (j <= end) {
arrB[k] = arr[j];
j++;
k++;
}
// Call the setData method once, outside of the for loop
s.setData(arr);
k = 0;
for (int i = begin; i <= end; i++) {
arr[i] = arrB[k];
k++;
}
}
```