我是C的初学者,我不确定如何跨方法访问变量。例如:
void merge_sort(int * a, int n) {
int *aux = (int*) malloc(n*sizeof(int));
sort(a, n);
free(aux);
}
当我尝试执行此操作时,编译器告诉我aux
无法访问sort
。那么我该如何解决这个问题呢?我将aux
设为全局变量吗?或者我使用extern
?
以下是我的其余代码:
void sort(long int *a, long int *aux, int low, int high) {
int size = high - low;
if (size <= INSERTION_THRESHOLD) {
insertion_sort(a + low, size);
}
else {
if (high <= low) {
return;
}
int mid = low + (high - low)/2;
sort(a, aux, low, mid);
sort(a, aux, mid + 1, high);
merge(a, aux, low , mid, high);
}
}
void merge(long int *a, long int *aux, int low, int mid, int high) {
int i = low;
int j = mid + 1;
for (int k = low; k <= high; k++) {
*(aux + k) = *(a + k);
}
for (int k = low; k <= high; k++) {
if (i > mid) {
*(a + k) = *(aux + (j++));
}
else if (j > high) {
*(a + k) = *(aux + (i++));
}
else if (aux[j] < aux[i]) {
*(a + k) = *(aux + (j++));
}
else {
*(a + k) = *(aux + (i++));
}
}