2

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);        
        }
    }
}
1
  • 1
    In the very implementation you provided, you do not need to copy an array, each level of recursion modifies its own element. Commented Apr 18, 2013 at 22:24

3 Answers 3

4

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 */
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for answer! Let's say that the number of recursive calls are a LOT, is some other way preferred or is this the way to go?
@sporetrans The preferred way is not to copy the array over and over.
@H2CO3 How would you solve it recursively without having to copy the array? Not that is is a must that the function has to be recursive. So doing it this way (wrapping array in struct) is not "good" programming practice in a sense? Thanks
3

If you need pass by value, you could always wrap your array into a structure and pass that. Keep in mind that your now struct contained array still needs to be big enough to handle all cases.

1 Comment

:-) Right. You get +1 from me for the first reason (and because it's correct).
3

Wrap it in a struct.

typedef struct arr_wrp {
    int arr[128]; // whatever
} arr_wrp;

void recFunc(arr_wrp arr, int step) {
    // do stuff, then
    arr.arr[step] = i;
    recFunc(arr, step + 1);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.