我为合并制作了以下c程序。然后我在我的系统上使用gcc compier执行它,它给出了一个分段错误。我无法弄清楚程序中导致此错误的原因。请帮忙。
#include<stdio.h>
void mergersort(int A[], int, int);
void merge(int A[], int, int, int);
void merge(int A[], int middle, int p, int q) {
int buffer1[30], buffer2[30], i, j, k, n1, n2;
n1 = middle-p+1;
n2 = q-middle;
for (i = p; i <= middle; i++) {
buffer1[i-p] = A[i];
}
for (j = middle+1; j <= q; j++) {
buffer2[j-i] = A[j];
}
i = 0; j = middle; k = 0;
while (i!=n1 || j!=n2) {
if (buffer1[i] <= buffer2[j]) A[k++] = buffer1[i++];
else A[k++] = buffer2[j++];
}
while (i != n1) {
A[k++] = buffer1[i++];
}
while (j != n2) {
A[k++] = buffer2[j++];
}
}
void mergesort(int A[], int p, int q) {
if (p < q) {
int middle = (p+q)/2;
mergesort(A,p,middle);
mergesort(A,middle+1,q);
merge(A,middle,p,q);
}
}
int main() {
int A[] = {56,23,33,1}, i;
mergesort(A,0,3);
for (i = 0; i < 4; i++)
printf("%d", A[i]);
return 0;
}
更新:我解决了这个问题。我应该多关注一下。除了我改变||后解决的分段错误到&amp;&amp;,输出不正确。合并过程中的k = 0,而不是k = 0。
答案 0 :(得分:1)
在merge()内部分配i,j,k
i = 0; j = middle; k = 0;
while (i!=n1 || j!=n2) { ...
应更改为此
i = 0; j = 0; k = p;
while (i!=n1 && j!=n2) {...
答案 1 :(得分:1)
更改此代码:
if (buffer1[i] <= buffer2[j]) A[k++] = buffer1[i++];
else A[k++] = buffer2[j++];
到此:
if (buffer1[i] <= buffer2[j]) {
printf("in if : i = %d : k = %d\n", i, k);
A[k++] = buffer1[i++];
} else {
A[k++] = buffer2[j++];
}
现在运行你的程序。在发生分段错误时,请参阅您尝试用于访问阵列的索引:
in if : i = 516 : k = 528
Segmentation fault: 11
现在你确定你的问题了。