0
我試圖排序終日的代碼合併,但我想不通爲什麼它不工作:( 我有一個SIGSEGV無論我做什麼合併排序SEGV,數組指針消失?
這裏是堆棧跟蹤:
#0 0x00401435 in tabLen (tab=0x1) at CodeBlocks\mergeSort.c:7
#1 0x004014d8 in mergeTabs (tab1=0x1, tab2=0x1) at CodeBlocks\mergeSort.c:26
#2 0x004016b3 in mergeSort (tab=0x3f1000, size=2) at CodeBlocks\mergeSort.c:51
#3 0x0040168b in mergeSort (tab=0x3f0fd8, size=3) at CodeBlocks\mergeSort.c:51
#4 0x0040168b in mergeSort (tab=0x3f2fb0, size=5) at CodeBlocks\mergeSort.c:51
#5 0x004013ea in main() at CodeBlocks\main.c:9
之間#1和#2,它就像陣列已經消失了,我不明白爲什麼...
這裏是我試過的實現:
int tabLen(int *tab)
{
int i = 0;
for (; tab && tab[i] && tab[i] != ENDTAB; ++i)
;
return i;
}
int *copy(int *tab, int beg, int end)
{
int size = end - beg + 1;
int *res = malloc(size * sizeof(int));
int i = beg;
for (; i < end; ++i)
res[i - beg] = tab[i];
res[i - beg] = ENDTAB;
return res;
}
int *mergeTabs(int *tab1, int *tab2)
{
int len1 = tabLen(tab1);
int len2 = tabLen(tab2);
int *res = malloc((len1 > len2) ? (len1+1) * sizeof(int) : (len2+1) * sizeof(int));
int i = 0;
int t1 = 0;
int t2 = 0;
printf("len1:%d | len2:%d\n", tabLen(tab1), tabLen(tab2));
for (; t1 < len1 && t2 < len2; ++i)
res[i] = (tab1[t1] < tab2[t2]) ? tab1[t1++] : tab2[t2++];
while (t1 < len1)
res[i++] = tab1[t1++];
while (t2 < len2)
res[i++] = tab2[t2++];
res[i] = ENDTAB;
return res;
}
int *mergeSort(int *tab, int size)
{
int *t1 = copy(tab, 0, size/2);
int *t2 = copy(tab, size/2, size);
if (tabLen(tab) <= 1)
return;
return mergeTabs(mergeSort(t1, tabLen(t1)), mergeSort(t2, tabLen(t2)));
}
任何想法?
感謝, 弗洛裏安
嗨,是ENDTAB等於-1! – Florian