sporetrans
sporetrans

Reputation: 35

Pass array by value to recursive function possible?

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);        
        }
    }
}

Upvotes: 2

Views: 1762

Answers (3)

user529758
user529758

Reputation:

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);
}

Upvotes: 3

Michael Dorgan
Michael Dorgan

Reputation: 12515

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.

Upvotes: 3

Kerrek SB
Kerrek SB

Reputation: 477408

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

Upvotes: 4

Related Questions