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

标签 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);         

}

Blockquote

最佳答案

使用“clang -Wall”编译时,您会收到以下警告:

warning: all paths through this function will call itself [-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));
}

关于c - 如何在c中的递归算法中通过引用传递参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50206880/

相关文章:

sorting - CMD 命令以递归方式列出具有排序顺序的文件夹中的所有文件,而不考虑层次结构中的位置?

python - python中的阶乘递归和迭代

arrays - 如何循环遍历数组作为引用?

java - 如何在满足特定条件后从递归中退出并返回对象

JavaScript 反射(reflect)所有对象引用中的属性更改

postgresql - postgres 获取数据,其中两列引用相同的父 ID

c中的char指针导致段错误

c - 509 最小字符限制的理由

c - sprintf 数组中指针的可变数量

c - C中的指针数组实现