Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

c - 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);        
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...