1. ## What is problem about the sorting?

The merge sort is written by myself
Code:
```#include <stdio.h>
#include <stdlib.h>

void merge(int *a, int p, int q, int r)
{
int n1 = q-p+1;
int n2 = r-q;
int *L = (int*)malloc((n1+1)*sizeof(int));
int *R = (int*)malloc((n2+1)*sizeof(int));
int i, j, k;
for (i = 0; i < n1; i++)
L[i] = a[p+i];
for (j = 0; j < n2; j++)
R[j] = a[q+j];
L[n1+1] = -1;
R[n2+1] = -1;
i = 0;
j = 0;
for (k = p; k < r; k++)
if (L[i] <= R[j]) {
a[k] = L[i];
i++;
}
else {
a[k] = R[j];
j++;
}
free(L);
free(R);
}

void merge_sort(int *a, int p, int r)
{
if (p < r) {
int q = (int)((p+r)/2);
merge_sort(a, p, q);
printf("asdfasd\n");
merge_sort(a, q+1, r);
printf("haha\n");
merge(a, p, q, r);
}
}

int main()
{
int i, n;
int *a;
printf("n = ");
scanf("%d", &n);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
merge_sort(a, 0, n-1);
for (i = 0; i < n; i++)
printf("%d ", a[i]);
return 0;
}```
Why doesn't this code work fine? Which step do i make wrong?

2. Code:
```int main()
{
int i, n;
int *a;
printf("n = ");
scanf("%d", &n);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
merge_sort(a, 0, n-1);
for (i = 0; i < n; i++)
printf("%d ", a[i]);
return 0;
}```
Danger Will Robinson!

Your pointer doesn't actually point to anything. Well, it does, but that's purely random. You haven't allocated anything at all for it. It's just a pointer. The next problem you're going to have is that you're trying to change what pointers point at inside a function. You'll have to use pointers to pointers for that to work out right.

But again, the real problem is your pointer doesn't actually point any place valid.

Quzah.

3. Originally Posted by quzah
Code:
```int main()
{
int i, n;
int *a;
printf("n = ");
scanf("%d", &n);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
merge_sort(a, 0, n-1);
for (i = 0; i < n; i++)
printf("%d ", a[i]);
return 0;
}```
Danger Will Robinson!

Your pointer doesn't actually point to anything. Well, it does, but that's purely random. You haven't allocated anything at all for it. It's just a pointer. The next problem you're going to have is that you're trying to change what pointers point at inside a function. You'll have to use pointers to pointers for that to work out right.

But again, the real problem is your pointer doesn't actually point any place valid.

Quzah.
I forgot to write this:
Code:
`*a = (int)malloc((n+1)*sizeof(int));`
Thanks for pointing the wrong place. But The merge sort is wrong on some place. where do i fix it?