错误分段错误 - 为什么我的代码不断地无限调用我的递归函数?

目标:在 L.H.S 上排列数组的负元素,在 R.H.S 上排列正元素

使用:递归

使用的数据类型:我使用过数组,但它在一个结构内,即数组 ADT

错误:分段错误

#include <stdio.h>
#include <stdlib.h>

struct Array 
{
    int a[10];
    int len;
};

void swap(int *a,int *b)
{
    int temp;
    temp = *a;
    *a = *b;
    *b = temp;
}

void NegativeSort(struct Array *arr,int i,int j)
{

    if(i < j)
    {
    
        if(arr-> a[i] > 0 && arr-> a[j] <= 0)
        {
            swap(&arr-> a[i],&arr-> a[j]);
            NegativeSort(arr,i++,j--);
        }
    
        else if(arr-> a[i] >= 0)
            NegativeSort(arr,i,j--);
    
        else
            NegativeSort(arr,j);
    }
}


int main()
{
    struct Array arr = {{-1,2,-3,4,-5,6,-7,8},8};
           
    NegativeSort(&arr,7);
    
    printf("elements are : ");
    for(i = 0; i < arr.len - 1; i++)
        printf("%d",arr.a[i]);
    
    return 0;
    
}
laji2525 回答:错误分段错误 - 为什么我的代码不断地无限调用我的递归函数?

如果在 NegativeSort 的递归调用中添加自增和自减运算符,则您可以使用它。您从 main 调用 NegativeSort(arr,7)。如果调用 NegativeSort(arr,i,j--);那么该调用的参数将再次是 (arr,7),因为 j-- 的值与 j 相同。最好调用 NegativeSort(arr,j-1);与 NegativeSort(arr,i++,j) 类似,它应该是 NegativeSort(arr,i+1,j)

本文链接:https://www.f2er.com/1807.html

大家都在问