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 */
}
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