如何在c中的递归算法中通过引用传递参数?

时间:2018-05-07 03:55:11

标签: c recursion reference

给定数组的

算法通过递归传递最大数,但是通过引用传递结果。

tam:数组的大小

首先我通过价值实现它并且它对我有用但是我需要通过参考结果传递它,我真的不知道错误是什么,如果你可以引导我,因为在编译它时,我做了不归还任何东西

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


void search(int a[], int tam, int max,int *result);

int main()
{
    int max,tam=5, result; 
    int array[5]={3,1,5,8,6};

    max=array[0];

    search(array, tam, max, &result);

    printf("the biggest number is: %d",result);
    return 0;

}


void search(int a[], int tam, int max, int *result )
{   
    if(tam==1)
        *result=max;


    if(max<a[tam-1])
        max=a[tam-1];       
        search(a,tam-1,max,result);         

}
  

块引用

2 个答案:

答案 0 :(得分:2)

使用'clang -Wall'进行编译时,会收到以下警告:

  

警告:通过此函数的所有路径都将调用自身[-Winfinite-recursion]

事实上,您的功能中没有有效的基本情况归纳步骤

我建议转换为以下内容:

#define MAX(x, y) ((x) > (y)) ? x : y

int search(int a[], int tam )
{   
    // base case if last element
    if (tam == 1) return a[0];  

    // inductive case (max of this and following elements)
    return MAX(a[0], search(a + 1, tam - 1));
}

答案 1 :(得分:0)

由于OP的代码试图是尾递归的,而@Gill Bates 's answer是头递归的,所以我展示了一个尾递归解决方案。

int find_max_helper(const int *a, int n, int max)
{
    if (n==0) return max;
    else return find_max_helper(a+1, n-1, MAX(max, a[0]));
}

//returns the maximum value in the array of size n elements
//or 0 if the array is empty
int find_max(const int *a, int n)
{
    return n > 0 ? find_max_helper(a+1, n-1, a[0]) : 0;
}