按值递归函数可能传递数组? [英] Pass array by value to recursive function possible?

查看:195
本文介绍了按值递归函数可能传递数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写建立了一个问题的所有可能的解决方案的递归函数。我在想,我应该通过一个数组,然后在每个递归步骤,将其设置为在递归步骤可能所有的值,但随后我就开始想,如果这是可能的,因为C会传递一个指针数组。你如何通常处理?

我在想沿着这些路线的东西。该阵列将取决于选择什么样的路径有很多不同的值。我们真的希望是按值传递数组,我猜。

  recFunc为(int *阵列,诠释recursiveStep){
    的for(int i = 0; I< A;我++){
        如果(stopCondition){
            做一点事;
        }
        否则如果(条件){
            数组[recursiveStep] =我;
            recFunc(数组,recursiveStep + 1);
        }
    }
}


解决方案

您可以通过贴成一个结构按值传递数组:

 结构foo的{int类型的[10]; };无效递归(结构富F)
{
    F.A [1] * = 2;
    递归(F); / *进行复印* /
}

I want to write a recursive function that builds up all possible solutions to a problem. I was thinking that I should pass an array and then, in each recursive step, set it to all values possible in that recursive step, but then I started wondering if this was possible, since C passes an array by passing a pointer. How do you typically deal with this?

I'm thinking something along these lines. The array will take many different values depending on what path is chosen. What we really would want is passing the array by value, I guess.

recFunc(int* array, int recursiveStep) {
    for (int i = 0; i < a; i++) {
        if (stopCondition) {
            doSomething;    
        }
        else if (condition) {
            array[recursiveStep] = i;
            recFunc(array, recursiveStep+1);        
        }
    }
}

解决方案

You can pass an array by value by sticking it into a struct:

struct foo { int a[10]; };

void recurse(struct foo f)
{
    f.a[1] *= 2;
    recurse(f);    /* makes a copy */
}

这篇关于按值递归函数可能传递数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆