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);        
        }
    }
}
dierre
  • 7,140
  • 12
  • 75
  • 120
sporetrans
  • 35
  • 3
  • 1
    In the very implementation you provided, you do not need to copy an array, each level of recursion modifies its own element. – Ixanezis Apr 18 '13 at 22:24

3 Answers3

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 */
}
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • 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 Apr 18 '13 at 22:26
  • 1
    @sporetrans The preferred way is not to copy the array over and over. –  Apr 18 '13 at 22:27
  • @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 – sporetrans Apr 19 '13 at 07:37
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.

Michael Dorgan
  • 12,453
  • 3
  • 31
  • 61
  • 1
    :-) Right. You get +1 from me for the first reason (and because it's correct). –  Apr 18 '13 at 22:25
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);
}