将数组作为参数传递给c时出现分段错误

时间:2013-03-10 20:55:31

标签: c segmentation-fault

作为一项任务,我必须实施mergesort。当我将数组作为参数传递时,我遇到了分段错误。一切似乎都是正确的。我附上了代码 arrint arr[1000],我将其传递给mergesort mergesort(arr, 0, n);

剩余代码如下。

void merge(int a[], int l, int m, int r)
{
    int temp[r -l];
    int templ = l;
    int tempm = m;
    register int k; 
    for(k=0; k<(r-l); k++)
    {
    if((tempm >= r)||(templ < m)&&(a[templ] <= a[tempm]))
    {   /*if number from left subarray is smaller*/
    temp[k] = a[templ];
    templ++;
    }
    else
    {   /*number from right subarray is smaller*/
    temp[k] = a[tempm];
    tempm++;
    }
    }
    for(k= l; k< r; k++)
    {   /*copy results back to the array to be returned*/
    a[k] = temp[k - l];
    }
}

void mergesort(int ar[], int left, int right)
{
    int mid;    
    if(left < right)
    {
    mid= (left + right)/2;
    mergesort(&ar[0], left, mid - 1);
    mergesort(&ar[0], mid, right);
    merge(&ar[0], left, mid, right);
    }
}

1 个答案:

答案 0 :(得分:1)

left == 0中有right == 1mergesort之后,您将获得无限递归:

void mergesort(int ar[], int left, int right) // IF LEFT IS 0 AND RIGHT IS 1 HERE...
{
    int mid;    
    if(left < right) // ...THEN LEFT IS LESS THAN RIGHT AND...
    {
    mid= (left + right)/2;
    mergesort(&ar[0], left, mid - 1);
    mergesort(&ar[0], mid, right); // ...HERE WE HAVE A CALL THAT IS
    // IDENTICAL TO THE ONE THAT GOT US HERE, INFINITE RECURSION